<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Settings - CertMate</title>
    <link rel="icon" type="image/x-icon" href="/favicon.ico">
    <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico">
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        /* Prevent flash of white background in dark mode */
        @media (prefers-color-scheme: dark) {
            html {
                background-color: #111827 !important;
            }
        }
    </style>
    <script>
        tailwind.config = {
            darkMode: 'media', // Automatically respects system preference
            theme: {
                extend: {
                    colors: {
                        primary: '#3b82f6',
                        secondary: '#1e40af',
                    }
                }
            }
        }
    </script>
</head>
<body class="bg-gray-50 dark:bg-gray-700/50 dark:bg-gray-900 min-h-screen transition-colors duration-200">
    <!-- Navigation -->
    <nav class="bg-white dark:bg-gray-800 shadow-sm border-b dark:border-gray-700">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between h-16">
                <div class="flex items-center">
                    <div class="flex-shrink-0">
                        <i class="fas fa-shield-alt text-primary text-2xl"></i>
                    </div>
                    <div class="ml-3">
                        <h1 class="text-xl font-semibold text-gray-900 dark:text-white">CertMate</h1>
                        <p class="text-sm text-gray-500 dark:text-gray-400">SSL Certificate Manager</p>
                    </div>
                </div>
                <div class="flex items-center space-x-4">
                    <a href="/" class="px-3 py-2 rounded-md text-sm font-medium text-gray-600 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white hover:bg-gray-100 dark:hover:bg-gray-700">
                        <i class="fas fa-certificate mr-1"></i> Certificates
                    </a>
                    <a href="/settings" class="px-3 py-2 rounded-md text-sm font-medium text-primary bg-blue-50 dark:bg-blue-900/20 dark:bg-blue-900/30 border border-blue-200 dark:border-blue-600 dark:border-blue-700">
                        <i class="fas fa-cog mr-1"></i> Settings
                    </a>
                    <a href="/help" class="px-3 py-2 rounded-md text-sm font-medium text-gray-600 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white hover:bg-gray-100 dark:hover:bg-gray-700">
                        <i class="fas fa-question-circle mr-1"></i> Help
                    </a>
                </div>
            </div>
        </div>
    </nav>

    <!-- Main Content -->
    <div class="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
        <!-- Header -->
        <div class="bg-white dark:bg-gray-800 shadow rounded-lg mb-6">
            <div class="px-6 py-4">
                <h2 class="text-2xl font-bold text-gray-900 dark:text-white">Settings</h2>
                <p class="text-gray-600 dark:text-gray-300 mt-1">Configure your DNS provider credentials and preferences</p>
                <div class="mt-3 flex items-center text-sm">
                    <div class="flex items-center text-green-600 dark:text-green-400" id="connectionStatus" style="display: none;">
                        <i class="fas fa-check-circle mr-1"></i>
                        <span>Connected and configured</span>
                    </div>
                    <div class="flex items-center text-yellow-600 dark:text-yellow-400" id="partialStatus" style="display: none;">
                        <i class="fas fa-exclamation-triangle mr-1"></i>
                        <span>Partially configured</span>
                    </div>
                    <div class="flex items-center text-red-600 dark:text-red-400" id="disconnectedStatus" style="display: none;">
                        <i class="fas fa-times-circle mr-1"></i>
                        <span>Not configured</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Settings Form -->
        <div class="bg-white dark:bg-gray-800 shadow rounded-lg">
            <div class="px-6 py-4 border-b dark:border-gray-700">
                <h3 class="text-lg font-medium text-gray-900 dark:text-white">Configuration</h3>
            </div>
            <div class="px-6 py-6">
                <form id="settingsForm" class="space-y-8">
                    
                    <!-- DNS Provider Selection -->
                    <div class="bg-gray-50 dark:bg-gray-700/50 p-4 rounded-lg">
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3" id="dns-provider-label">
                            <i class="fas fa-server mr-1"></i>
                            DNS Providers
                        </label>
                        
                        <!-- Multi-Account Providers -->
                        <div class="mb-6">
                            <h4 class="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2 flex items-center">
                                <i class="fas fa-users mr-2 text-blue-500"></i>
                                Multi-Account Support
                                <span class="ml-2 text-xs bg-blue-100 dark:bg-blue-900/30 text-blue-800 dark:text-blue-300 px-2 py-0.5 rounded-full">Advanced</span>
                            </h4>
                            <div class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 xl:grid-cols-7 gap-2 mb-4" role="radiogroup" aria-labelledby="dns-provider-label">
                                <label class="relative">
                                    <input type="radio" name="dns_provider" value="cloudflare" class="sr-only peer">
                                    <div class="p-2 border-2 border-gray-200 dark:border-gray-600 rounded-lg cursor-pointer transition-all peer-checked:border-primary peer-checked:bg-blue-50 dark:bg-blue-900/20 dark:peer-checked:bg-blue-900/30 hover:border-gray-300 dark:hover:border-gray-500">
                                        <div class="text-center">
                                            <i class="fab fa-cloudflare text-lg text-orange-500 mb-1"></i>
                                            <div class="text-xs font-medium dark:text-white">Cloudflare</div>
                                            <div class="text-xs text-gray-500 dark:text-gray-400 mt-1" id="cloudflare-status">Not configured</div>
                                            <!-- Multi-account indicator -->
                                            <div class="text-xs text-blue-600 dark:text-blue-400 mt-1 hidden" id="cloudflare-accounts">
                                                <i class="fas fa-users text-xs mr-1"></i>
                                                <span id="cloudflare-account-count">0</span> accounts
                                            </div>
                                        </div>
                                    </div>
                                </label>
                                <label class="relative">
                                    <input type="radio" name="dns_provider" value="route53" class="sr-only peer">
                                    <div class="p-2 border-2 border-gray-200 dark:border-gray-600 rounded-lg cursor-pointer transition-all peer-checked:border-primary peer-checked:bg-blue-50 dark:bg-blue-900/20 dark:peer-checked:bg-blue-900/30 hover:border-gray-300 dark:hover:border-gray-500">
                                        <div class="text-center">
                                            <i class="fab fa-aws text-lg text-orange-400 mb-1"></i>
                                            <div class="text-xs font-medium dark:text-white">Route53</div>
                                            <div class="text-xs text-gray-500 dark:text-gray-400 mt-1" id="route53-status">Not configured</div>
                                            <!-- Multi-account indicator -->
                                            <div class="text-xs text-blue-600 dark:text-blue-400 mt-1 hidden" id="route53-accounts">
                                                <i class="fas fa-users text-xs mr-1"></i>
                                                <span id="route53-account-count">0</span> accounts
                                            </div>
                                        </div>
                                    </div>
                                </label>
                                <label class="relative">
                                    <input type="radio" name="dns_provider" value="digitalocean" class="sr-only peer">
                                    <div class="p-2 border-2 border-gray-200 dark:border-gray-600 rounded-lg cursor-pointer transition-all peer-checked:border-primary peer-checked:bg-blue-50 dark:bg-blue-900/20 dark:peer-checked:bg-blue-900/30 hover:border-gray-300 dark:hover:border-gray-500">
                                        <div class="text-center">
                                            <i class="fab fa-digital-ocean text-lg text-blue-600 mb-1"></i>
                                            <div class="text-xs font-medium dark:text-white">DigitalOcean</div>
                                            <div class="text-xs text-gray-500 dark:text-gray-400 mt-1" id="digitalocean-status">Not configured</div>
                                            <!-- Multi-account indicator -->
                                            <div class="text-xs text-blue-600 dark:text-blue-400 mt-1 hidden" id="digitalocean-accounts">
                                                <i class="fas fa-users text-xs mr-1"></i>
                                                <span id="digitalocean-account-count">0</span> accounts
                                            </div>
                                        </div>
                                    </div>
                                </label>
                                <label class="relative">
                                    <input type="radio" name="dns_provider" value="azure" class="sr-only peer">
                                    <div class="p-2 border-2 border-gray-200 dark:border-gray-600 rounded-lg cursor-pointer transition-all peer-checked:border-primary peer-checked:bg-blue-50 dark:bg-blue-900/20 dark:peer-checked:bg-blue-900/30 hover:border-gray-300 dark:hover:border-gray-500">
                                        <div class="text-center">
                                            <i class="fab fa-microsoft text-lg text-blue-600 mb-1"></i>
                                            <div class="text-xs font-medium dark:text-white">Azure DNS</div>
                                            <div class="text-xs text-gray-500 dark:text-gray-400 mt-1" id="azure-status">Not configured</div>
                                            <!-- Multi-account indicator -->
                                            <div class="text-xs text-blue-600 dark:text-blue-400 mt-1 hidden" id="azure-accounts">
                                                <i class="fas fa-users text-xs mr-1"></i>
                                                <span id="azure-account-count">0</span> accounts
                                            </div>
                                        </div>
                                    </div>
                                </label>
                                <label class="relative">
                                    <input type="radio" name="dns_provider" value="google" class="sr-only peer">
                                    <div class="p-2 border-2 border-gray-200 dark:border-gray-600 rounded-lg cursor-pointer transition-all peer-checked:border-primary peer-checked:bg-blue-50 dark:bg-blue-900/20 dark:peer-checked:bg-blue-900/30 hover:border-gray-300 dark:hover:border-gray-500">
                                        <div class="text-center">
                                            <i class="fab fa-google text-lg text-blue-500 mb-1"></i>
                                            <div class="text-xs font-medium dark:text-white">Google DNS</div>
                                            <div class="text-xs text-gray-500 dark:text-gray-400 mt-1" id="google-status">Not configured</div>
                                            <!-- Multi-account indicator -->
                                            <div class="text-xs text-blue-600 dark:text-blue-400 mt-1 hidden" id="google-accounts">
                                                <i class="fas fa-users text-xs mr-1"></i>
                                                <span id="google-account-count">0</span> accounts
                                            </div>
                                        </div>
                                    </div>
                                </label>
                                <label class="relative">
                                    <input type="radio" name="dns_provider" value="powerdns" class="sr-only peer">
                                    <div class="p-2 border-2 border-gray-200 dark:border-gray-600 rounded-lg cursor-pointer transition-all peer-checked:border-primary peer-checked:bg-blue-50 dark:bg-blue-900/20 dark:peer-checked:bg-blue-900/30 hover:border-gray-300 dark:hover:border-gray-500">
                                        <div class="text-center">
                                            <i class="fas fa-server text-lg text-gray-600 dark:text-gray-400 mb-1"></i>
                                            <div class="text-xs font-medium dark:text-white">PowerDNS</div>
                                            <div class="text-xs text-gray-500 dark:text-gray-400 mt-1" id="powerdns-status">Not configured</div>
                                            <!-- Multi-account indicator -->
                                            <div class="text-xs text-blue-600 dark:text-blue-400 mt-1 hidden" id="powerdns-accounts">
                                                <i class="fas fa-users text-xs mr-1"></i>
                                                <span id="powerdns-account-count">0</span> accounts
                                            </div>
                                        </div>
                                    </div>
                                </label>
                                <label class="relative">
                                    <input type="radio" name="dns_provider" value="rfc2136" class="sr-only peer">
                                    <div class="p-2 border-2 border-gray-200 dark:border-gray-600 rounded-lg cursor-pointer transition-all peer-checked:border-primary peer-checked:bg-blue-50 dark:bg-blue-900/20 dark:peer-checked:bg-blue-900/30 hover:border-gray-300 dark:hover:border-gray-500">
                                        <div class="text-center">
                                            <i class="fas fa-exchange-alt text-lg text-gray-600 dark:text-gray-400 mb-1"></i>
                                            <div class="text-xs font-medium dark:text-white">RFC2136</div>
                                            <div class="text-xs text-gray-500 dark:text-gray-400 mt-1" id="rfc2136-status">Not configured</div>
                                            <!-- Multi-account indicator -->
                                            <div class="text-xs text-blue-600 dark:text-blue-400 mt-1 hidden" id="rfc2136-accounts">
                                                <i class="fas fa-users text-xs mr-1"></i>
                                                <span id="rfc2136-account-count">0</span> accounts
                                            </div>
                                        </div>
                                    </div>
                                </label>
                            </div>
                        </div>
                        
                        <!-- Single-Account Providers -->
                        <div>
                            <h4 class="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2 flex items-center">
                                <i class="fas fa-user mr-2 text-gray-500"></i>
                                Single Account Providers
                                <span class="ml-2 text-xs bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 px-2 py-0.5 rounded-full">Standard</span>
                            </h4>
                            <div class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 xl:grid-cols-8 gap-2" role="radiogroup" aria-labelledby="dns-provider-label">
                                <label class="relative">
                                    <input type="radio" name="dns_provider" value="linode" class="sr-only peer">
                                    <div class="p-2 border-2 border-gray-200 dark:border-gray-600 rounded-lg cursor-pointer transition-all peer-checked:border-primary peer-checked:bg-blue-50 dark:bg-blue-900/20 dark:peer-checked:bg-blue-900/30 hover:border-gray-300 dark:hover:border-gray-500">
                                        <div class="text-center">
                                            <i class="fas fa-cloud text-lg text-green-600 mb-1"></i>
                                            <div class="text-xs font-medium dark:text-white">Linode</div>
                                            <div class="text-xs text-gray-500 dark:text-gray-400 mt-1" id="linode-status">Not configured</div>
                                        </div>
                                    </div>
                                </label>
                                <label class="relative">
                                    <input type="radio" name="dns_provider" value="vultr" class="sr-only peer">
                                    <div class="p-2 border-2 border-gray-200 dark:border-gray-600 rounded-lg cursor-pointer transition-all peer-checked:border-primary peer-checked:bg-blue-50 dark:bg-blue-900/20 dark:peer-checked:bg-blue-900/30 hover:border-gray-300 dark:hover:border-gray-500">
                                        <div class="text-center">
                                            <i class="fas fa-cloud text-lg text-blue-600 mb-1"></i>
                                            <div class="text-xs font-medium dark:text-white">Vultr</div>
                                            <div class="text-xs text-gray-500 dark:text-gray-400 mt-1" id="vultr-status">Not configured</div>
                                        </div>
                                    </div>
                                </label>
                                <label class="relative">
                                    <input type="radio" name="dns_provider" value="hetzner" class="sr-only peer">
                                    <div class="p-2 border-2 border-gray-200 dark:border-gray-600 rounded-lg cursor-pointer transition-all peer-checked:border-primary peer-checked:bg-blue-50 dark:bg-blue-900/20 dark:peer-checked:bg-blue-900/30 hover:border-gray-300 dark:hover:border-gray-500">
                                        <div class="text-center">
                                            <i class="fas fa-server text-lg text-red-600 mb-1"></i>
                                            <div class="text-xs font-medium dark:text-white">Hetzner</div>
                                            <div class="text-xs text-gray-500 dark:text-gray-400 mt-1" id="hetzner-status">Not configured</div>
                                        </div>
                                    </div>
                                </label>
                                <label class="relative">
                                    <input type="radio" name="dns_provider" value="gandi" class="sr-only peer">
                                    <div class="p-2 border-2 border-gray-200 dark:border-gray-600 rounded-lg cursor-pointer transition-all peer-checked:border-primary peer-checked:bg-blue-50 dark:bg-blue-900/20 dark:peer-checked:bg-blue-900/30 hover:border-gray-300 dark:hover:border-gray-500">
                                        <div class="text-center">
                                            <i class="fas fa-globe text-lg text-orange-600 mb-1"></i>
                                            <div class="text-xs font-medium dark:text-white">Gandi</div>
                                            <div class="text-xs text-gray-500 dark:text-gray-400 mt-1" id="gandi-status">Not configured</div>
                                        </div>
                                    </div>
                                </label>
                                <label class="relative">
                                    <input type="radio" name="dns_provider" value="ovh" class="sr-only peer">
                                    <div class="p-2 border-2 border-gray-200 dark:border-gray-600 rounded-lg cursor-pointer transition-all peer-checked:border-primary peer-checked:bg-blue-50 dark:bg-blue-900/20 dark:peer-checked:bg-blue-900/30 hover:border-gray-300 dark:hover:border-gray-500">
                                        <div class="text-center">
                                            <i class="fas fa-server text-lg text-purple-600 mb-1"></i>
                                            <div class="text-xs font-medium dark:text-white">OVH</div>
                                            <div class="text-xs text-gray-500 dark:text-gray-400 mt-1" id="ovh-status">Not configured</div>
                                        </div>
                                    </div>
                                </label>
                                <label class="relative">
                                    <input type="radio" name="dns_provider" value="namecheap" class="sr-only peer">
                                    <div class="p-2 border-2 border-gray-200 dark:border-gray-600 rounded-lg cursor-pointer transition-all peer-checked:border-primary peer-checked:bg-blue-50 dark:bg-blue-900/20 dark:peer-checked:bg-blue-900/30 hover:border-gray-300 dark:hover:border-gray-500">
                                        <div class="text-center">
                                            <i class="fas fa-shopping-cart text-lg text-red-600 mb-1"></i>
                                            <div class="text-xs font-medium dark:text-white">Namecheap</div>
                                            <div class="text-xs text-gray-500 dark:text-gray-400 mt-1" id="namecheap-status">Not configured</div>
                                        </div>
                                    </div>
                                </label>
                                <label class="relative">
                                    <input type="radio" name="dns_provider" value="porkbun" class="sr-only peer">
                                    <div class="p-2 border-2 border-gray-200 dark:border-gray-600 rounded-lg cursor-pointer transition-all peer-checked:border-primary peer-checked:bg-blue-50 dark:bg-blue-900/20 dark:peer-checked:bg-blue-900/30 hover:border-gray-300 dark:hover:border-gray-500">
                                        <div class="text-center">
                                            <i class="fas fa-paw text-lg text-pink-600 mb-1"></i>
                                            <div class="text-xs font-medium dark:text-white">Porkbun</div>
                                            <div class="text-xs text-gray-500 dark:text-gray-400 mt-1" id="porkbun-status">Not configured</div>
                                        </div>
                                    </div>
                                </label>
                                <label class="relative">
                                    <input type="radio" name="dns_provider" value="godaddy" class="sr-only peer">
                                    <div class="p-2 border-2 border-gray-200 dark:border-gray-600 rounded-lg cursor-pointer transition-all peer-checked:border-primary peer-checked:bg-blue-50 dark:bg-blue-900/20 dark:peer-checked:bg-blue-900/30 hover:border-gray-300 dark:hover:border-gray-500">
                                        <div class="text-center">
                                            <i class="fas fa-globe text-lg text-green-600 mb-1"></i>
                                            <div class="text-xs font-medium dark:text-white">GoDaddy</div>
                                            <div class="text-xs text-gray-500 dark:text-gray-400 mt-1" id="godaddy-status">Not configured</div>
                                        </div>
                                    </div>
                                </label>
                                <label class="relative">
                                    <input type="radio" name="dns_provider" value="dnsmadeeasy" class="sr-only peer">
                                    <div class="p-2 border-2 border-gray-200 dark:border-gray-600 rounded-lg cursor-pointer transition-all peer-checked:border-primary peer-checked:bg-blue-50 dark:bg-blue-900/20 dark:peer-checked:bg-blue-900/30 hover:border-gray-300 dark:hover:border-gray-500">
                                        <div class="text-center">
                                            <i class="fas fa-cogs text-lg text-green-600 mb-1"></i>
                                            <div class="text-xs font-medium dark:text-white">DNS Made Easy</div>
                                            <div class="text-xs text-gray-500 dark:text-gray-400 mt-1" id="dnsmadeeasy-status">Not configured</div>
                                        </div>
                                    </div>
                                </label>
                                <label class="relative">
                                    <input type="radio" name="dns_provider" value="nsone" class="sr-only peer">
                                    <div class="p-2 border-2 border-gray-200 dark:border-gray-600 rounded-lg cursor-pointer transition-all peer-checked:border-primary peer-checked:bg-blue-50 dark:bg-blue-900/20 dark:peer-checked:bg-blue-900/30 hover:border-gray-300 dark:hover:border-gray-500">
                                        <div class="text-center">
                                            <i class="fas fa-network-wired text-lg text-indigo-600 mb-1"></i>
                                            <div class="text-xs font-medium dark:text-white">NS1</div>
                                            <div class="text-xs text-gray-500 dark:text-gray-400 mt-1" id="nsone-status">Not configured</div>
                                        </div>
                                    </div>
                                </label>
                                <label class="relative">
                                    <input type="radio" name="dns_provider" value="he-ddns" class="sr-only peer">
                                    <div class="p-2 border-2 border-gray-200 dark:border-gray-600 rounded-lg cursor-pointer transition-all peer-checked:border-primary peer-checked:bg-blue-50 dark:bg-blue-900/20 dark:peer-checked:bg-blue-900/30 hover:border-gray-300 dark:hover:border-gray-500">
                                        <div class="text-center">
                                            <i class="fas fa-bolt text-lg text-yellow-600 mb-1"></i>
                                            <div class="text-xs font-medium dark:text-white">Hurricane Electric</div>
                                            <div class="text-xs text-gray-500 dark:text-gray-400 mt-1" id="he-ddns-status">Not configured</div>
                                        </div>
                                    </div>
                                </label>
                                <label class="relative">
                                    <input type="radio" name="dns_provider" value="dynudns" class="sr-only peer">
                                    <div class="p-2 border-2 border-gray-200 dark:border-gray-600 rounded-lg cursor-pointer transition-all peer-checked:border-primary peer-checked:bg-blue-50 dark:bg-blue-900/20 dark:peer-checked:bg-blue-900/30 hover:border-gray-300 dark:hover:border-gray-500">
                                        <div class="text-center">
                                            <i class="fas fa-sync-alt text-lg text-purple-600 mb-1"></i>
                                            <div class="text-xs font-medium dark:text-white">Dynu</div>
                                            <div class="text-xs text-gray-500 dark:text-gray-400 mt-1" id="dynudns-status">Not configured</div>
                                        </div>
                                    </div>
                                </label>
                            </div>
                        </div>
                    </div>

                    <!-- DNS Provider Configurations -->
                    <!-- Cloudflare Configuration -->
                    <div id="cloudflare-config" class="dns-config hidden">
                        <div class="border border-orange-200 dark:border-orange-600 rounded-lg p-4 bg-orange-50 dark:bg-orange-900/20">
                            <div class="flex items-center justify-between mb-4">
                                <h4 class="text-lg font-medium text-gray-900 dark:text-white">
                                    <i class="fab fa-cloudflare mr-2 text-orange-500"></i>
                                    Cloudflare Configuration
                                </h4>
                                <button type="button" id="cloudflare-add-account" onclick="showAddAccountModal('cloudflare')" 
                                        class="inline-flex items-center px-3 py-1.5 border border-transparent text-xs font-medium rounded-md text-white bg-primary hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                                    <i class="fas fa-plus mr-1"></i>
                                    Add Account
                                </button>
                            </div>
                            
                            <!-- Account Management List -->
                            <div id="cloudflare-accounts-list" class="space-y-3 mb-4">
                                <!-- Accounts will be populated here -->
                            </div>
                            
                            <!-- Legacy single account fields (hidden when multi-account mode is active) -->
                            <div id="cloudflare-legacy-config">
                                <label for="cloudflare_api_token" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                                    API Token
                                </label>
                                <div class="mt-1">
                                    <input type="password" id="cloudflare_api_token" name="cloudflare_api_token" 
                                           class="block w-full border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary"
                                           placeholder="Enter your Cloudflare API token"
                                           autocomplete="new-password" 
                                           spellcheck="false"
                                           data-lpignore="true">
                                </div>
                                <p class="mt-2 text-sm text-gray-600 dark:text-gray-300">
                                    Create an API token at <a href="https://dash.cloudflare.com/profile/api-tokens" target="_blank" class="text-primary hover:underline">Cloudflare Dashboard</a> with <strong>Zone:DNS:Edit</strong> permissions.
                                </p>
                            </div>
                        </div>
                    </div>

                    <!-- AWS Route53 Configuration -->
                    <div id="route53-config" class="dns-config hidden">
                        <div class="border border-orange-200 dark:border-orange-600 rounded-lg p-4 bg-orange-50 dark:bg-orange-900/20">
                            <div class="flex items-center justify-between mb-4">
                                <h4 class="text-lg font-medium text-gray-900 dark:text-white">
                                    <i class="fab fa-aws mr-2 text-orange-400"></i>
                                    AWS Route53 Configuration
                                </h4>
                                <button type="button" id="route53-add-account" onclick="showAddAccountModal('route53')" 
                                        class="inline-flex items-center px-3 py-1.5 border border-transparent text-xs font-medium rounded-md text-white bg-primary hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                                    <i class="fas fa-plus mr-1"></i>
                                    Add Account
                                </button>
                            </div>
                            
                            <!-- Account Management List -->
                            <div id="route53-accounts-list" class="space-y-3 mb-4">
                                <!-- Accounts will be populated here -->
                            </div>
                            
                            <!-- Legacy single account fields (hidden when multi-account mode is active) -->
                            <div id="route53-legacy-config">
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <div>
                                        <label for="route53_access_key_id" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                                            Access Key ID
                                        </label>
                                        <input type="password" id="route53_access_key_id" name="route53_access_key_id" 
                                               class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary"
                                               placeholder="AKIAIOSFODNN7EXAMPLE"
                                               autocomplete="new-password" 
                                               spellcheck="false"
                                               data-lpignore="true">
                                    </div>
                                    <div>
                                        <label for="route53_secret_access_key" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                                            Secret Access Key
                                        </label>
                                        <input type="password" id="route53_secret_access_key" name="route53_secret_access_key" 
                                               class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary"
                                               placeholder="Your AWS secret access key"
                                               autocomplete="new-password" 
                                               spellcheck="false"
                                               data-lpignore="true">
                                    </div>
                                    <div>
                                        <label for="route53_region" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                                            Region (Optional)
                                        </label>
                                        <input type="text" id="route53_region" name="route53_region" 
                                               class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary"
                                               placeholder="us-east-1" value="us-east-1">
                                    </div>
                                </div>
                                <p class="mt-2 text-sm text-gray-600 dark:text-gray-300">
                                    Create IAM credentials with <strong>Route53FullAccess</strong> policy or a custom policy with Route53 DNS permissions.
                                </p>
                            </div>
                        </div>
                    </div>

                    <!-- Azure DNS Configuration -->
                    <div id="azure-config" class="dns-config hidden">
                        <div class="border border-orange-200 dark:border-orange-600 rounded-lg p-4 bg-orange-50 dark:bg-orange-900/20">
                            <div class="flex items-center justify-between mb-4">
                                <h4 class="text-lg font-medium text-gray-900 dark:text-white">
                                    <i class="fab fa-microsoft mr-2 text-blue-600"></i>
                                    Azure DNS Configuration
                                </h4>
                                <button type="button" id="azure-add-account" onclick="showAddAccountModal('azure')" 
                                        class="inline-flex items-center px-3 py-1.5 border border-transparent text-xs font-medium rounded-md text-white bg-primary hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                                    <i class="fas fa-plus mr-1"></i>
                                    Add Account
                                </button>
                            </div>
                            
                            <!-- Account Management List -->
                            <div id="azure-accounts-list" class="space-y-3 mb-4">
                                <!-- Accounts will be populated here -->
                            </div>
                            
                            <!-- Legacy single account fields (hidden when multi-account mode is active) -->
                            <div id="azure-legacy-config">
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <div>
                                        <label for="azure_subscription_id" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                                            Subscription ID
                                        </label>
                                        <input type="text" id="azure_subscription_id" name="azure_subscription_id" 
                                               class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary"
                                               placeholder="12345678-1234-1234-1234-123456789012">
                                    </div>
                                    <div>
                                        <label for="azure_resource_group" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                                            Resource Group
                                        </label>
                                        <input type="text" id="azure_resource_group" name="azure_resource_group" 
                                               class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary"
                                               placeholder="my-dns-resource-group">
                                    </div>
                                    <div>
                                        <label for="azure_tenant_id" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                                            Tenant ID
                                        </label>
                                        <input type="text" id="azure_tenant_id" name="azure_tenant_id" 
                                               class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary"
                                               placeholder="12345678-1234-1234-1234-123456789012">
                                    </div>
                                    <div>
                                        <label for="azure_client_id" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                                            Client ID
                                        </label>
                                        <input type="text" id="azure_client_id" name="azure_client_id" 
                                               class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary"
                                               placeholder="12345678-1234-1234-1234-123456789012">
                                    </div>
                                    <div class="md:col-span-2">
                                        <label for="azure_client_secret" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                                            Client Secret
                                        </label>
                                        <input type="password" id="azure_client_secret" name="azure_client_secret" 
                                               class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary"
                                               placeholder="Your Azure client secret"
                                               autocomplete="new-password" 
                                               spellcheck="false"
                                               data-lpignore="true">
                                    </div>
                                </div>
                                <p class="mt-2 text-sm text-gray-600 dark:text-gray-300">
                                    Create a Service Principal with <strong>DNS Zone Contributor</strong> role for your DNS zones.
                                </p>
                            </div>
                        </div>
                    </div>

                    <!-- Google Cloud DNS Configuration -->
                    <div id="google-config" class="dns-config hidden">
                        <div class="border border-orange-200 dark:border-orange-600 rounded-lg p-4 bg-orange-50 dark:bg-orange-900/20">
                            <div class="flex items-center justify-between mb-4">
                                <h4 class="text-lg font-medium text-gray-900 dark:text-white">
                                    <i class="fab fa-google mr-2 text-blue-500"></i>
                                    Google Cloud DNS Configuration
                                </h4>
                                <button type="button" id="google-add-account" onclick="showAddAccountModal('google')" 
                                        class="inline-flex items-center px-3 py-1.5 border border-transparent text-xs font-medium rounded-md text-white bg-primary hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                                    <i class="fas fa-plus mr-1"></i>
                                    Add Account
                                </button>
                            </div>
                            
                            <!-- Account Management List -->
                            <div id="google-accounts-list" class="space-y-3 mb-4">
                                <!-- Accounts will be populated here -->
                            </div>
                            
                            <!-- Legacy single account fields (hidden when multi-account mode is active) -->
                            <div id="google-legacy-config">
                                <div class="space-y-4">
                                    <div>
                                        <label for="google_project_id" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                                            Project ID
                                        </label>
                                        <input type="text" id="google_project_id" name="google_project_id" 
                                               class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary"
                                               placeholder="my-gcp-project-123456">
                                    </div>
                                    <div>
                                        <label for="google_service_account_key" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                                            Service Account JSON Key
                                        </label>
                                        <textarea id="google_service_account_key" name="google_service_account_key" rows="4"
                                               class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary"
                                               placeholder='{"type": "service_account", "project_id": "...", ...}'></textarea>
                                    </div>
                                </div>
                                <p class="mt-2 text-sm text-gray-600 dark:text-gray-300">
                                    Create a Service Account with <strong>DNS Administrator</strong> role and download the JSON key file.
                                </p>
                            </div>
                        </div>
                    </div>

                    <!-- PowerDNS Configuration -->
                    <div id="powerdns-config" class="dns-config hidden">
                        <div class="border border-orange-200 dark:border-orange-600 rounded-lg p-4 bg-orange-50 dark:bg-orange-900/20">
                            <div class="flex items-center justify-between mb-4">
                                <h4 class="text-lg font-medium text-gray-900 dark:text-white">
                                    <i class="fas fa-server mr-2 text-gray-600"></i>
                                    PowerDNS Configuration
                                </h4>
                                <button type="button" id="powerdns-add-account" onclick="showAddAccountModal('powerdns')" 
                                        class="inline-flex items-center px-3 py-1.5 border border-transparent text-xs font-medium rounded-md text-white bg-primary hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                                    <i class="fas fa-plus mr-1"></i>
                                    Add Account
                                </button>
                            </div>
                            
                            <!-- Account Management List -->
                            <div id="powerdns-accounts-list" class="space-y-3 mb-4">
                                <!-- Accounts will be populated here -->
                            </div>
                            
                            <!-- Legacy single account fields (hidden when multi-account mode is active) -->
                            <div id="powerdns-legacy-config">
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <div>
                                        <label for="powerdns_api_url" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                                            API URL
                                        </label>
                                        <input type="url" id="powerdns_api_url" name="powerdns_api_url" 
                                               class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary"
                                               placeholder="https://powerdns.example.com:8081">
                                    </div>
                                    <div>
                                        <label for="powerdns_api_key" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                                            API Key
                                        </label>
                                        <input type="password" id="powerdns_api_key" name="powerdns_api_key" 
                                               class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary"
                                               placeholder="Your PowerDNS API key"
                                               autocomplete="new-password" 
                                               spellcheck="false"
                                               data-lpignore="true">
                                    </div>
                                </div>
                                <p class="mt-2 text-sm text-gray-600 dark:text-gray-300">
                                    Configure your PowerDNS server with API access enabled and provide the API endpoint and key.
                                </p>
                            </div>
                        </div>
                    </div>

                    <!-- DigitalOcean Configuration -->
                    <div id="digitalocean-config" class="dns-config hidden">
                        <div class="border border-orange-200 dark:border-orange-600 rounded-lg p-4 bg-orange-50 dark:bg-orange-900/20">
                            <div class="flex items-center justify-between mb-4">
                                <h4 class="text-lg font-medium text-gray-900 dark:text-white">
                                    <i class="fab fa-digital-ocean mr-2 text-blue-600"></i>
                                    DigitalOcean DNS Configuration
                                </h4>
                                <button type="button" id="digitalocean-add-account" onclick="showAddAccountModal('digitalocean')" 
                                        class="inline-flex items-center px-3 py-1.5 border border-transparent text-xs font-medium rounded-md text-white bg-primary hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                                    <i class="fas fa-plus mr-1"></i>
                                    Add Account
                                </button>
                            </div>
                            
                            <!-- Account Management List -->
                            <div id="digitalocean-accounts-list" class="space-y-3 mb-4">
                                <!-- Accounts will be populated here -->
                            </div>
                            
                            <!-- Legacy single account fields (hidden when multi-account mode is active) -->
                            <div id="digitalocean-legacy-config">
                                <div class="grid grid-cols-1 gap-4">
                                    <div>
                                        <label for="digitalocean_api_token" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                                            API Token
                                        </label>
                                        <input type="password" id="digitalocean_api_token" name="digitalocean_api_token" 
                                               class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary"
                                               placeholder="Your DigitalOcean API token"
                                               autocomplete="new-password" 
                                               spellcheck="false"
                                               data-lpignore="true">
                                    </div>
                                </div>
                                <p class="mt-2 text-sm text-gray-600 dark:text-gray-300">
                                    Generate a personal access token from your DigitalOcean control panel with read/write permissions for DNS.
                                </p>
                            </div>
                        </div>
                    </div>

                    <!-- Vultr Configuration -->
                    <div id="vultr-config" class="dns-config hidden">
                        <div class="border border-orange-200 dark:border-orange-600 rounded-lg p-4 bg-orange-50 dark:bg-orange-900/20">
                            <div class="flex items-center justify-between mb-4">
                                <h4 class="text-lg font-medium text-gray-900 dark:text-white">
                                    <i class="fas fa-cloud mr-2 text-blue-600"></i>
                                    Vultr DNS Configuration
                                </h4>
                                <button type="button" id="vultr-add-account" onclick="showAddAccountModal('vultr')" 
                                        class="inline-flex items-center px-3 py-1.5 border border-transparent text-xs font-medium rounded-md text-white bg-primary hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                                    <i class="fas fa-plus mr-1"></i>
                                    Add Account
                                </button>
                            </div>
                            
                            <!-- Account Management List -->
                            <div id="vultr-accounts-list" class="space-y-3 mb-4">
                                <!-- Accounts will be populated here -->
                            </div>
                            
                            <!-- Legacy single account fields (hidden when multi-account mode is active) -->
                            <div id="vultr-legacy-config">
                                <label for="vultr_api_key" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                                    API Key
                                </label>
                                <div class="mt-1">
                                    <input type="password" id="vultr_api_key" name="vultr_api_key" 
                                           class="block w-full border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary"
                                           placeholder="Enter your Vultr API key">
                                </div>
                                <p class="mt-2 text-sm text-gray-600 dark:text-gray-300">
                                    Generate an API key from your Vultr control panel with DNS permissions.
                                </p>
                            </div>
                        </div>
                    </div>

                    <!-- Linode Configuration -->
                    <div id="linode-config" class="dns-config hidden">
                        <div class="border border-orange-200 dark:border-orange-600 rounded-lg p-4 bg-orange-50 dark:bg-orange-900/20">
                            <h4 class="text-lg font-medium text-gray-900 dark:text-white mb-4">
                                <i class="fas fa-cloud mr-2 text-green-600"></i>
                                Linode DNS Configuration
                            </h4>
                            <div class="grid grid-cols-1 gap-4">
                                <div>
                                    <label for="linode_api_key" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                                        API Key
                                    </label>
                                    <input type="password" id="linode_api_key" name="linode_api_key" 
                                           class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary"
                                           placeholder="Your Linode API key">
                                </div>
                            </div>
                            <p class="mt-2 text-sm text-gray-600 dark:text-gray-300">
                                Create a personal access token from your Linode account with read/write access to DNS records.
                            </p>
                        </div>
                    </div>

                    <!-- Gandi Configuration -->
                    <div id="gandi-config" class="dns-config hidden">
                        <div class="border border-orange-200 dark:border-orange-600 rounded-lg p-4 bg-orange-50 dark:bg-orange-900/20">
                            <h4 class="text-lg font-medium text-gray-900 dark:text-white mb-4">
                                <i class="fas fa-globe mr-2 text-orange-600"></i>
                                Gandi DNS Configuration
                            </h4>
                            <div class="grid grid-cols-1 gap-4">
                                <div>
                                    <label for="gandi_api_token" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                                        API Token
                                    </label>
                                    <input type="password" id="gandi_api_token" name="gandi_api_token" 
                                           class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary"
                                           placeholder="Your Gandi LiveDNS API token">
                                </div>
                            </div>
                            <p class="mt-2 text-sm text-gray-600 dark:text-gray-300">
                                Generate a personal access token from your Gandi account with DNS access permissions.
                            </p>
                        </div>
                    </div>

                    <!-- OVH Configuration -->
                    <div id="ovh-config" class="dns-config hidden">
                        <div class="border border-orange-200 dark:border-orange-600 rounded-lg p-4 bg-orange-50 dark:bg-orange-900/20">
                            <h4 class="text-lg font-medium text-gray-900 dark:text-white mb-4">
                                <i class="fas fa-server mr-2 text-purple-600"></i>
                                OVH DNS Configuration
                            </h4>
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div>
                                    <label for="ovh_endpoint" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                                        Endpoint
                                    </label>
                                    <select id="ovh_endpoint" name="ovh_endpoint" 
                                            class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary">
                                        <option value="">Select endpoint</option>
                                        <option value="ovh-eu">ovh-eu (Europe)</option>
                                        <option value="ovh-us">ovh-us (US)</option>
                                        <option value="ovh-ca">ovh-ca (Canada)</option>
                                        <option value="kimsufi-eu">kimsufi-eu</option>
                                        <option value="kimsufi-ca">kimsufi-ca</option>
                                        <option value="soyoustart-eu">soyoustart-eu</option>
                                        <option value="soyoustart-ca">soyoustart-ca</option>
                                    </select>
                                </div>
                                <div>
                                    <label for="ovh_application_key" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                                        Application Key
                                    </label>
                                    <input type="password" id="ovh_application_key" name="ovh_application_key" 
                                           class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary"
                                           placeholder="Your application key">
                                </div>
                                <div>
                                    <label for="ovh_application_secret" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                                        Application Secret
                                    </label>
                                    <input type="password" id="ovh_application_secret" name="ovh_application_secret" 
                                           class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary"
                                           placeholder="Your application secret">
                                </div>
                                <div>
                                    <label for="ovh_consumer_key" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                                        Consumer Key
                                    </label>
                                    <input type="password" id="ovh_consumer_key" name="ovh_consumer_key" 
                                           class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary"
                                           placeholder="Your consumer key">
                                </div>
                            </div>
                            <p class="mt-2 text-sm text-gray-600 dark:text-gray-300">
                                Create an OVH application with DNS access permissions and configure the API credentials.
                            </p>
                        </div>
                    </div>

                    <!-- Namecheap Configuration -->
                    <div id="namecheap-config" class="dns-config hidden">
                        <div class="border border-orange-200 dark:border-orange-600 rounded-lg p-4 bg-orange-50 dark:bg-orange-900/20">
                            <h4 class="text-lg font-medium text-gray-900 dark:text-white mb-4">
                                <i class="fas fa-shopping-cart mr-2 text-red-600"></i>
                                Namecheap DNS Configuration
                            </h4>
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div>
                                    <label for="namecheap_username" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                                        Username
                                    </label>
                                    <input type="text" id="namecheap_username" name="namecheap_username" 
                                           class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary"
                                           placeholder="Your Namecheap username">
                                </div>
                                <div>
                                    <label for="namecheap_api_key" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                                        API Key
                                    </label>
                                    <input type="password" id="namecheap_api_key" name="namecheap_api_key" 
                                           class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary"
                                           placeholder="Your Namecheap API key">
                                </div>
                            </div>
                            <p class="mt-2 text-sm text-gray-600 dark:text-gray-300">
                                Enable API access in your Namecheap account and provide your username and API key.
                            </p>
                        </div>
                    </div>

                    <!-- RFC2136 Configuration -->
                    <div id="rfc2136-config" class="dns-config hidden">
                        <div class="border border-orange-200 dark:border-orange-600 rounded-lg p-4 bg-orange-50 dark:bg-orange-900/20">
                            <div class="flex items-center justify-between mb-4">
                                <h4 class="text-lg font-medium text-gray-900 dark:text-white">
                                    <i class="fas fa-exchange-alt mr-2 text-gray-600"></i>
                                    RFC2136 DNS Configuration
                                </h4>
                                <button type="button" id="rfc2136-add-account" onclick="showAddAccountModal('rfc2136')" 
                                        class="inline-flex items-center px-3 py-1.5 border border-transparent text-xs font-medium rounded-md text-white bg-primary hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                                    <i class="fas fa-plus mr-1"></i>
                                    Add Server
                                </button>
                            </div>
                            
                            <!-- Account Management List -->
                            <div id="rfc2136-accounts-list" class="space-y-3 mb-4">
                                <!-- Accounts will be populated here -->
                            </div>
                            
                            <!-- Legacy single account fields (hidden when multi-account mode is active) -->
                            <div id="rfc2136-legacy-config">
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <div>
                                        <label for="rfc2136_nameserver" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                                            Nameserver
                                        </label>
                                        <input type="text" id="rfc2136_nameserver" name="rfc2136_nameserver" 
                                               class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary"
                                               placeholder="ns.example.com">
                                    </div>
                                    <div>
                                        <label for="rfc2136_tsig_key" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                                            TSIG Key Name
                                        </label>
                                        <input type="text" id="rfc2136_tsig_key" name="rfc2136_tsig_key" 
                                               class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary"
                                               placeholder="mykey">
                                    </div>
                                    <div>
                                        <label for="rfc2136_tsig_secret" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                                            TSIG Secret
                                        </label>
                                        <input type="password" id="rfc2136_tsig_secret" name="rfc2136_tsig_secret" 
                                               class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary"
                                               placeholder="Base64-encoded secret">
                                    </div>
                                    <div>
                                        <label for="rfc2136_tsig_algorithm" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                                            TSIG Algorithm (Optional)
                                        </label>
                                        <select id="rfc2136_tsig_algorithm" name="rfc2136_tsig_algorithm" 
                                                class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary">
                                            <option value="">Default (HMAC-MD5)</option>
                                            <option value="HMAC-MD5">HMAC-MD5</option>
                                            <option value="HMAC-SHA1">HMAC-SHA1</option>
                                            <option value="HMAC-SHA224">HMAC-SHA224</option>
                                            <option value="HMAC-SHA256">HMAC-SHA256</option>
                                            <option value="HMAC-SHA384">HMAC-SHA384</option>
                                            <option value="HMAC-SHA512">HMAC-SHA512</option>
                                        </select>
                                    </div>
                                </div>
                                <p class="mt-2 text-sm text-gray-600 dark:text-gray-300">
                                    Configure RFC2136 dynamic DNS updates for BIND or compatible DNS servers.
                                </p>
                            </div>
                        </div>
                    </div>

                    <!-- Additional Provider Configurations -->
                    
                    <!-- Hetzner Configuration -->
                    <div id="hetzner-config" class="dns-config hidden">
                        <div class="border border-orange-200 dark:border-orange-600 rounded-lg p-4 bg-orange-50 dark:bg-orange-900/20">
                            <h4 class="text-lg font-medium text-gray-900 dark:text-white mb-4">
                                <i class="fas fa-server mr-2 text-red-600"></i>
                                Hetzner DNS Configuration
                            </h4>
                            <div>
                                <label for="hetzner_api_token" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                                    API Token
                                </label>
                                <input type="password" id="hetzner_api_token" name="hetzner_api_token" 
                                       class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary"
                                       placeholder="Your Hetzner DNS API token">
                            </div>
                            <p class="mt-2 text-sm text-gray-600 dark:text-gray-300">
                                Create an API token at <a href="https://dns.hetzner.com/" target="_blank" class="text-primary hover:underline">Hetzner DNS Console</a> with DNS zone permissions.
                            </p>
                        </div>
                    </div>

                    <!-- Porkbun Configuration -->
                    <div id="porkbun-config" class="dns-config hidden">
                        <div class="border border-orange-200 dark:border-orange-600 rounded-lg p-4 bg-orange-50 dark:bg-orange-900/20">
                            <h4 class="text-lg font-medium text-gray-900 dark:text-white mb-4">
                                <i class="fas fa-paw mr-2 text-pink-600"></i>
                                Porkbun DNS Configuration
                            </h4>
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div>
                                    <label for="porkbun_api_key" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                                        API Key
                                    </label>
                                    <input type="password" id="porkbun_api_key" name="porkbun_api_key" 
                                           class="mt-1 block w-full border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary"
                                           placeholder="Your Porkbun API key">
                                </div>
                                <div>
                                    <label for="porkbun_secret_key" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                                        Secret Key
                                    </label>
                                    <input type="password" id="porkbun_secret_key" name="porkbun_secret_key" 
                                           class="mt-1 block w-full border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary"
                                           placeholder="Your Porkbun secret key">
                                </div>
                            </div>
                            <p class="mt-2 text-sm text-gray-600 dark:text-gray-300">
                                Get your API credentials from <a href="https://porkbun.com/account/api" target="_blank" class="text-primary hover:underline">Porkbun API page</a>.
                            </p>
                        </div>
                    </div>

                    <!-- GoDaddy Configuration -->
                    <div id="godaddy-config" class="dns-config hidden">
                        <div class="border border-orange-200 dark:border-orange-600 rounded-lg p-4 bg-orange-50 dark:bg-orange-900/20">
                            <h4 class="text-lg font-medium text-gray-900 dark:text-white mb-4">
                                <i class="fas fa-globe mr-2 text-green-600"></i>
                                GoDaddy DNS Configuration
                            </h4>
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div>
                                    <label for="godaddy_api_key" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                                        API Key
                                    </label>
                                    <input type="password" id="godaddy_api_key" name="godaddy_api_key" 
                                           class="mt-1 block w-full border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary"
                                           placeholder="Your GoDaddy API key">
                                </div>
                                <div>
                                    <label for="godaddy_secret" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                                        API Secret
                                    </label>
                                    <input type="password" id="godaddy_secret" name="godaddy_secret" 
                                           class="mt-1 block w-full border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary"
                                           placeholder="Your GoDaddy API secret">
                                </div>
                            </div>
                            <p class="mt-2 text-sm text-gray-600 dark:text-gray-300">
                                Create API credentials at <a href="https://developer.godaddy.com/keys" target="_blank" class="text-primary hover:underline">GoDaddy Developer Portal</a>.
                            </p>
                        </div>
                    </div>

                    <!-- Hurricane Electric Configuration -->
                    <div id="he-ddns-config" class="dns-config hidden">
                        <div class="border border-orange-200 dark:border-orange-600 rounded-lg p-4 bg-orange-50 dark:bg-orange-900/20">
                            <h4 class="text-lg font-medium text-gray-900 dark:text-white mb-4">
                                <i class="fas fa-bolt mr-2 text-yellow-600"></i>
                                Hurricane Electric DNS Configuration
                            </h4>
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div>
                                    <label for="he_ddns_username" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                                        Username
                                    </label>
                                    <input type="text" id="he_ddns_username" name="he_ddns_username" 
                                           class="mt-1 block w-full border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary"
                                           placeholder="Your Hurricane Electric username">
                                </div>
                                <div>
                                    <label for="he_ddns_password" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                                        Password
                                    </label>
                                    <input type="password" id="he_ddns_password" name="he_ddns_password" 
                                           class="mt-1 block w-full border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary"
                                           placeholder="Your Hurricane Electric password">
                                </div>
                            </div>
                            <p class="mt-2 text-sm text-gray-600 dark:text-gray-300">
                                Use your <a href="https://dns.he.net/" target="_blank" class="text-primary hover:underline">Hurricane Electric DNS</a> account credentials.
                            </p>
                        </div>
                    </div>

                    <!-- Dynu Configuration -->
                    <div id="dynudns-config" class="dns-config hidden">
                        <div class="border border-orange-200 dark:border-orange-600 rounded-lg p-4 bg-orange-50 dark:bg-orange-900/20">
                            <h4 class="text-lg font-medium text-gray-900 dark:text-white mb-4">
                                <i class="fas fa-sync-alt mr-2 text-purple-600"></i>
                                Dynu DNS Configuration
                            </h4>
                            <div>
                                <label for="dynudns_token" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                                    API Token
                                </label>
                                <input type="password" id="dynudns_token" name="dynudns_token" 
                                       class="mt-1 block w-full border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary"
                                       placeholder="Your Dynu API token">
                            </div>
                            <p class="mt-2 text-sm text-gray-600 dark:text-gray-300">
                                Generate an API token at <a href="https://www.dynu.com/en-US/ControlPanel/APICredentials" target="_blank" class="text-primary hover:underline">Dynu Control Panel</a>.
                            </p>
                        </div>
                    </div>

                    <!-- CA Providers Section -->
                    <div class="bg-gray-50 dark:bg-gray-700/50 p-4 rounded-lg">
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
                            <i class="fas fa-certificate mr-1"></i>
                            Certificate Authority (CA) Providers
                        </label>
                        
                        <div class="space-y-4">
                            <!-- Default CA Selection -->
                            <div>
                                <label class="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-2">
                                    Default Certificate Authority
                                </label>
                                <select id="default-ca" name="default_ca" 
                                        class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary dark:bg-gray-700 dark:text-white text-sm"
                                        onchange="toggleCAProviderConfig()">
                                    <option value="letsencrypt">Let's Encrypt (Default)</option>
                                    <option value="digicert">DigiCert ACME</option>
                                    <option value="private_ca">Private CA</option>
                                </select>
                                <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">
                                    Select the default CA for new certificate requests. You can override this per-certificate.
                                </p>
                            </div>

                            <!-- CA Provider Configurations -->
                            
                            <!-- Let's Encrypt Configuration -->
                            <div id="letsencrypt-config" class="border border-green-300 dark:border-green-600 rounded-lg p-4 bg-green-50 dark:bg-green-900/20">
                                <h4 class="text-sm font-semibold text-green-800 dark:text-green-200 mb-2 flex items-center">
                                    <i class="fas fa-leaf mr-2 text-green-600"></i>
                                    Let's Encrypt Configuration
                                    <span class="ml-2 text-xs bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-300 px-2 py-0.5 rounded-full">Free</span>
                                </h4>
                                <div class="space-y-3">
                                    <div>
                                        <label class="block text-xs text-green-800 dark:text-green-200 mb-1">Environment</label>
                                        <select id="letsencrypt-environment" 
                                                class="w-full px-2 py-1 text-sm border border-green-300 dark:border-green-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white">
                                            <option value="production">Production (Default)</option>
                                            <option value="staging">Staging (Testing)</option>
                                        </select>
                                    </div>
                                    <div>
                                        <label class="block text-xs text-green-800 dark:text-green-200 mb-1">Email (for notifications)</label>
                                        <input type="email" id="letsencrypt-email" 
                                               class="w-full px-2 py-1 text-sm border border-green-300 dark:border-green-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                                               placeholder="admin@example.com">
                                    </div>
                                </div>
                                <p class="text-xs text-green-700 dark:text-green-300 mt-2">
                                    Let's Encrypt provides free SSL certificates with automated renewal.
                                </p>
                            </div>

                            <!-- DigiCert Configuration -->
                            <div id="digicert-config" class="border border-blue-300 dark:border-blue-600 rounded-lg p-4 bg-blue-50 dark:bg-blue-900/20" style="display: none;">
                                <h4 class="text-sm font-semibold text-blue-800 dark:text-blue-200 mb-2 flex items-center">
                                    <i class="fas fa-shield-alt mr-2 text-blue-600"></i>
                                    DigiCert ACME Configuration
                                    <span class="ml-2 text-xs bg-blue-100 dark:bg-blue-900/30 text-blue-800 dark:text-blue-300 px-2 py-0.5 rounded-full">Enterprise</span>
                                </h4>
                                <div class="space-y-3">
                                    <div>
                                        <label class="block text-xs text-blue-800 dark:text-blue-200 mb-1">ACME Directory URL</label>
                                        <input type="url" id="digicert-acme-url" 
                                               class="w-full px-2 py-1 text-sm border border-blue-300 dark:border-blue-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                                               placeholder="https://acme.digicert.com/v2/acme/directory"
                                               value="https://acme.digicert.com/v2/acme/directory">
                                    </div>
                                    <div>
                                        <label class="block text-xs text-blue-800 dark:text-blue-200 mb-1">External Account Binding (EAB) Key ID</label>
                                        <input type="text" id="digicert-eab-kid" 
                                               class="w-full px-2 py-1 text-sm border border-blue-300 dark:border-blue-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                                               placeholder="Your EAB Key ID from DigiCert">
                                    </div>
                                    <div>
                                        <label class="block text-xs text-blue-800 dark:text-blue-200 mb-1">External Account Binding (EAB) HMAC Key</label>
                                        <input type="password" id="digicert-eab-hmac" 
                                               class="w-full px-2 py-1 text-sm border border-blue-300 dark:border-blue-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                                               placeholder="Your EAB HMAC Key from DigiCert"
                                               autocomplete="new-password" 
                                               spellcheck="false"
                                               data-lpignore="true">
                                    </div>
                                    <div>
                                        <label class="block text-xs text-blue-800 dark:text-blue-200 mb-1">Email (for notifications)</label>
                                        <input type="email" id="digicert-email" 
                                               class="w-full px-2 py-1 text-sm border border-blue-300 dark:border-blue-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                                               placeholder="admin@example.com">
                                    </div>
                                </div>
                                <p class="text-xs text-blue-700 dark:text-blue-300 mt-2">
                                    DigiCert provides enterprise-grade SSL certificates via ACME. Requires EAB credentials from DigiCert.
                                </p>
                            </div>

                            <!-- Private CA Configuration -->
                            <div id="private-ca-config" class="border border-purple-300 dark:border-purple-600 rounded-lg p-4 bg-purple-50 dark:bg-purple-900/20" style="display: none;">
                                <h4 class="text-sm font-semibold text-purple-800 dark:text-purple-200 mb-2 flex items-center">
                                    <i class="fas fa-building mr-2 text-purple-600"></i>
                                    Private CA Configuration
                                    <span class="ml-2 text-xs bg-purple-100 dark:bg-purple-900/30 text-purple-800 dark:text-purple-300 px-2 py-0.5 rounded-full">Custom</span>
                                </h4>
                                <div class="space-y-3">
                                    <div>
                                        <label class="block text-xs text-purple-800 dark:text-purple-200 mb-1">
                                            ACME Directory URL
                                            <span class="text-red-500">*</span>
                                            <i class="fas fa-info-circle ml-1 cursor-help" title="URL to your private CA's ACME directory endpoint (e.g., step-ca, Smallstep, or custom ACME server)"></i>
                                        </label>
                                        <input type="url" id="private-ca-acme-url" 
                                               class="w-full px-2 py-1 text-sm border-2 border-purple-300 dark:border-purple-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white focus:border-purple-500 focus:ring-2 focus:ring-purple-200"
                                               placeholder="https://step-ca.example.com:9000/acme/directory"
                                               required>
                                        <p class="text-xs text-purple-600 dark:text-purple-400 mt-1">
                                            <strong>Common examples:</strong><br>
                                            • step-ca: https://step-ca.internal.com:9000/acme/directory<br>
                                            • Smallstep: https://ca.example.com/acme/directory<br>
                                            • Boulder: https://boulder.local:4001/acme/directory
                                        </p>
                                    </div>
                                    <div>
                                        <label class="block text-xs text-purple-800 dark:text-purple-200 mb-1">CA Certificate (PEM format) - Optional</label>
                                        <textarea id="private-ca-cert" rows="3"
                                                  class="w-full px-2 py-1 text-sm border border-purple-300 dark:border-purple-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                                                  placeholder="-----BEGIN CERTIFICATE-----&#10;...&#10;-----END CERTIFICATE-----"></textarea>
                                        <p class="text-xs text-purple-600 dark:text-purple-400 mt-1">
                                            Upload your private CA root certificate if using self-signed or internal CA
                                        </p>
                                    </div>
                                    <div>
                                        <label class="block text-xs text-purple-800 dark:text-purple-200 mb-1">External Account Binding (EAB) Key ID - Optional</label>
                                        <input type="text" id="private-ca-eab-kid" 
                                               class="w-full px-2 py-1 text-sm border border-purple-300 dark:border-purple-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                                               placeholder="EAB Key ID (if required by your CA)">
                                    </div>
                                    <div>
                                        <label class="block text-xs text-purple-800 dark:text-purple-200 mb-1">External Account Binding (EAB) HMAC Key - Optional</label>
                                        <input type="password" id="private-ca-eab-hmac" 
                                               class="w-full px-2 py-1 text-sm border border-purple-300 dark:border-purple-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                                               placeholder="EAB HMAC Key (if required by your CA)"
                                               autocomplete="new-password" 
                                               spellcheck="false"
                                               data-lpignore="true">
                                    </div>
                                    <div>
                                        <label class="block text-xs text-purple-800 dark:text-purple-200 mb-1">
                                            Email (for notifications)
                                            <span class="text-red-500">*</span>
                                        </label>
                                        <input type="email" id="private-ca-email" 
                                               class="w-full px-2 py-1 text-sm border border-purple-300 dark:border-purple-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                                               placeholder="admin@example.com"
                                               required>
                                    </div>
                                </div>
                                <p class="text-xs text-purple-700 dark:text-purple-300 mt-2">
                                    Configure your private or corporate CA. Supports ACME-compatible CAs like step-ca, Smallstep, Boulder, and others.
                                    <br><strong>🚀 Quick Start:</strong>
                                    <br>1. Enter your CA's ACME directory URL above
                                    <br>2. Enter your email address
                                    <br>3. Click "Test CA Connection" to verify
                                    <br>4. Save settings once test succeeds
                                </p>
                            </div>

                            <!-- CA Provider Actions -->
                            <div class="flex flex-wrap gap-3 pt-2 border-t border-gray-200 dark:border-gray-600">
                                <button type="button" onclick="testCAProvider()" 
                                        class="bg-green-600 text-white px-4 py-2 rounded-md hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 transition-colors text-sm font-medium">
                                    <i class="fas fa-plug mr-1"></i> Test CA Connection
                                </button>
                                <div class="text-xs text-gray-500 dark:text-gray-400 flex items-center">
                                    <i class="fas fa-info-circle mr-1"></i>
                                    <span id="ca-test-hint">Select a CA provider and fill in required fields, then test the connection</span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- General Certificate Settings Section -->
                    <div class="bg-gray-50 dark:bg-gray-700/50 p-4 rounded-lg">
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
                            <i class="fas fa-cogs mr-1"></i>
                            Certificate Management Settings
                        </label>
                        
                        <div class="space-y-4">
                            <!-- Auto Renewal Setting -->
                            <div>
                                <label class="flex items-center">
                                    <input type="checkbox" id="auto_renew" name="auto_renew" 
                                           class="rounded border-gray-300 dark:border-gray-600 text-primary focus:ring-primary focus:ring-offset-0 dark:bg-gray-700">
                                    <span class="ml-2 text-sm text-gray-700 dark:text-gray-300">Enable automatic certificate renewal</span>
                                </label>
                                <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                                    Automatically renew certificates when they approach expiration
                                </p>
                            </div>
                            
                            <!-- Renewal Threshold Setting -->
                            <div>
                                <label class="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-2">
                                    Certificate Renewal Threshold (days)
                                </label>
                                <input type="number" id="renewal_threshold_days" name="renewal_threshold_days" 
                                       min="1" max="90" value="30"
                                       class="w-32 px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary dark:bg-gray-700 dark:text-white text-sm">
                                <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                                    Renew certificates when they have this many days left before expiration (default: 30 days)
                                </p>
                            </div>
                        </div>
                    </div>

                    <!-- Certificate Storage Backend Section -->
                    <div class="bg-gray-50 dark:bg-gray-700/50 p-4 rounded-lg">
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
                            <i class="fas fa-database mr-1"></i>
                            Certificate Storage Backend
                        </label>
                        
                        <div class="space-y-4">
                            <!-- Backend Selection -->
                            <div>
                                <label class="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-2">
                                    Storage Backend Type
                                </label>
                                <select id="storage-backend" name="storage_backend" 
                                        class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary dark:bg-gray-700 dark:text-white text-sm"
                                        onchange="toggleStorageBackendConfig()">
                                    <option value="local_filesystem">Local Filesystem (Default)</option>
                                    <option value="azure_keyvault">Azure Key Vault</option>
                                    <option value="aws_secrets_manager">AWS Secrets Manager</option>
                                    <option value="hashicorp_vault">HashiCorp Vault</option>
                                    <option value="infisical">Infisical</option>
                                </select>
                                <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                                    Choose where to store your SSL certificates. Local filesystem is the default and most compatible option.
                                </p>
                            </div>

                            <!-- Local Filesystem Configuration -->
                            <div id="storage-local-config" class="storage-config">
                                <div class="bg-blue-50 dark:bg-blue-900/20 p-3 rounded-md border border-blue-200 dark:border-blue-700">
                                    <h5 class="text-sm font-medium text-blue-900 dark:text-blue-100 mb-2">
                                        <i class="fas fa-folder mr-1"></i> Local Filesystem Storage
                                    </h5>
                                    <div class="space-y-2">
                                        <div>
                                            <label class="block text-xs text-blue-800 dark:text-blue-200 mb-1">Certificate Directory</label>
                                            <input type="text" id="storage-cert-dir" 
                                                   class="w-full px-2 py-1 text-sm border border-blue-300 dark:border-blue-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                                                   placeholder="certificates" value="certificates">
                                        </div>
                                        <p class="text-xs text-blue-700 dark:text-blue-300">
                                            Certificates are stored locally in the specified directory with secure file permissions.
                                        </p>
                                    </div>
                                </div>
                            </div>

                            <!-- Azure Key Vault Configuration -->
                            <div id="storage-azure-config" class="storage-config" style="display: none;">
                                <div class="bg-blue-50 dark:bg-blue-900/20 p-3 rounded-md border border-blue-200 dark:border-blue-700">
                                    <h5 class="text-sm font-medium text-blue-900 dark:text-blue-100 mb-2">
                                        <i class="fab fa-microsoft mr-1"></i> Azure Key Vault Configuration
                                    </h5>
                                    <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                                        <div>
                                            <label class="block text-xs text-blue-800 dark:text-blue-200 mb-1">Vault URL</label>
                                            <input type="text" id="azure-vault-url" 
                                                   class="w-full px-2 py-1 text-sm border border-blue-300 dark:border-blue-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                                                   placeholder="https://yourvault.vault.azure.net/">
                                        </div>
                                        <div>
                                            <label class="block text-xs text-blue-800 dark:text-blue-200 mb-1">Tenant ID</label>
                                            <input type="text" id="azure-tenant-id" 
                                                   class="w-full px-2 py-1 text-sm border border-blue-300 dark:border-blue-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                                                   placeholder="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx">
                                        </div>
                                        <div>
                                            <label class="block text-xs text-blue-800 dark:text-blue-200 mb-1">Client ID</label>
                                            <input type="text" id="azure-client-id" 
                                                   class="w-full px-2 py-1 text-sm border border-blue-300 dark:border-blue-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                                                   placeholder="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx">
                                        </div>
                                        <div>
                                            <label class="block text-xs text-blue-800 dark:text-blue-200 mb-1">Client Secret</label>
                                            <input type="password" id="azure-client-secret" 
                                                   class="w-full px-2 py-1 text-sm border border-blue-300 dark:border-blue-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                                                   placeholder="Enter client secret"
                                                   autocomplete="new-password" 
                                                   spellcheck="false"
                                                   data-lpignore="true">
                                        </div>
                                    </div>
                                    <p class="text-xs text-blue-700 dark:text-blue-300 mt-2">
                                        Certificates will be stored as secrets in Azure Key Vault with enhanced security and audit capabilities.
                                    </p>
                                </div>
                            </div>

                            <!-- AWS Secrets Manager Configuration -->
                            <div id="storage-aws-config" class="storage-config" style="display: none;">
                                <div class="bg-orange-50 dark:bg-orange-900/20 p-3 rounded-md border border-orange-200 dark:border-orange-700">
                                    <h5 class="text-sm font-medium text-orange-900 dark:text-orange-100 mb-2">
                                        <i class="fab fa-aws mr-1"></i> AWS Secrets Manager Configuration
                                    </h5>
                                    <div class="grid grid-cols-1 md:grid-cols-3 gap-3">
                                        <div>
                                            <label class="block text-xs text-orange-800 dark:text-orange-200 mb-1">Region</label>
                                            <input type="text" id="aws-region" 
                                                   class="w-full px-2 py-1 text-sm border border-orange-300 dark:border-orange-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                                                   placeholder="us-east-1" value="us-east-1">
                                        </div>
                                        <div>
                                            <label class="block text-xs text-orange-800 dark:text-orange-200 mb-1">Access Key ID</label>
                                            <input type="text" id="aws-access-key-id" 
                                                   class="w-full px-2 py-1 text-sm border border-orange-300 dark:border-orange-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                                                   placeholder="AKIAIOSFODNN7EXAMPLE">
                                        </div>
                                        <div>
                                            <label class="block text-xs text-orange-800 dark:text-orange-200 mb-1">Secret Access Key</label>
                                            <input type="password" id="aws-secret-access-key" 
                                                   class="w-full px-2 py-1 text-sm border border-orange-300 dark:border-orange-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                                                   placeholder="Enter secret access key"
                                                   autocomplete="new-password" 
                                                   spellcheck="false"
                                                   data-lpignore="true">
                                        </div>
                                    </div>
                                    <p class="text-xs text-orange-700 dark:text-orange-300 mt-2">
                                        Certificates will be stored in AWS Secrets Manager with automatic encryption and access logging.
                                    </p>
                                </div>
                            </div>

                            <!-- HashiCorp Vault Configuration -->
                            <div id="storage-vault-config" class="storage-config" style="display: none;">
                                <div class="bg-purple-50 dark:bg-purple-900/20 p-3 rounded-md border border-purple-200 dark:border-purple-700">
                                    <h5 class="text-sm font-medium text-purple-900 dark:text-purple-100 mb-2">
                                        <i class="fas fa-vault mr-1"></i> HashiCorp Vault Configuration
                                    </h5>
                                    <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                                        <div>
                                            <label class="block text-xs text-purple-800 dark:text-purple-200 mb-1">Vault URL</label>
                                            <input type="text" id="vault-url" 
                                                   class="w-full px-2 py-1 text-sm border border-purple-300 dark:border-purple-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                                                   placeholder="https://vault.example.com:8200">
                                        </div>
                                        <div>
                                            <label class="block text-xs text-purple-800 dark:text-purple-200 mb-1">Vault Token</label>
                                            <input type="password" id="vault-token" 
                                                   class="w-full px-2 py-1 text-sm border border-purple-300 dark:border-purple-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                                                   placeholder="Enter vault token"
                                                   autocomplete="new-password" 
                                                   spellcheck="false"
                                                   data-lpignore="true">
                                        </div>
                                        <div>
                                            <label class="block text-xs text-purple-800 dark:text-purple-200 mb-1">Mount Point</label>
                                            <input type="text" id="vault-mount-point" 
                                                   class="w-full px-2 py-1 text-sm border border-purple-300 dark:border-purple-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                                                   placeholder="secret" value="secret">
                                        </div>
                                        <div>
                                            <label class="block text-xs text-purple-800 dark:text-purple-200 mb-1">Engine Version</label>
                                            <select id="vault-engine-version" 
                                                    class="w-full px-2 py-1 text-sm border border-purple-300 dark:border-purple-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white">
                                                <option value="v2">KV v2</option>
                                                <option value="v1">KV v1</option>
                                            </select>
                                        </div>
                                    </div>
                                    <p class="text-xs text-purple-700 dark:text-purple-300 mt-2">
                                        Certificates will be stored in HashiCorp Vault's KV secrets engine with versioning and audit capabilities.
                                    </p>
                                </div>
                            </div>

                            <!-- Infisical Configuration -->
                            <div id="storage-infisical-config" class="storage-config" style="display: none;">
                                <div class="bg-green-50 dark:bg-green-900/20 p-3 rounded-md border border-green-200 dark:border-green-700">
                                    <h5 class="text-sm font-medium text-green-900 dark:text-green-100 mb-2">
                                        <i class="fas fa-shield-alt mr-1"></i> Infisical Configuration
                                    </h5>
                                    <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                                        <div>
                                            <label class="block text-xs text-green-800 dark:text-green-200 mb-1">Site URL</label>
                                            <input type="text" id="infisical-site-url" 
                                                   class="w-full px-2 py-1 text-sm border border-green-300 dark:border-green-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                                                   placeholder="https://app.infisical.com" value="https://app.infisical.com">
                                        </div>
                                        <div>
                                            <label class="block text-xs text-green-800 dark:text-green-200 mb-1">Project ID</label>
                                            <input type="text" id="infisical-project-id" 
                                                   class="w-full px-2 py-1 text-sm border border-green-300 dark:border-green-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                                                   placeholder="Enter project ID">
                                        </div>
                                        <div>
                                            <label class="block text-xs text-green-800 dark:text-green-200 mb-1">Client ID</label>
                                            <input type="text" id="infisical-client-id" 
                                                   class="w-full px-2 py-1 text-sm border border-green-300 dark:border-green-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                                                   placeholder="Enter client ID">
                                        </div>
                                        <div>
                                            <label class="block text-xs text-green-800 dark:text-green-200 mb-1">Client Secret</label>
                                            <input type="password" id="infisical-client-secret" 
                                                   class="w-full px-2 py-1 text-sm border border-green-300 dark:border-green-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                                                   placeholder="Enter client secret"
                                                   autocomplete="new-password" 
                                                   spellcheck="false"
                                                   data-lpignore="true">
                                        </div>
                                        <div>
                                            <label class="block text-xs text-green-800 dark:text-green-200 mb-1">Environment</label>
                                            <input type="text" id="infisical-environment" 
                                                   class="w-full px-2 py-1 text-sm border border-green-300 dark:border-green-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
                                                   placeholder="prod" value="prod">
                                        </div>
                                    </div>
                                    <p class="text-xs text-green-700 dark:text-green-300 mt-2">
                                        Certificates will be stored in Infisical with end-to-end encryption and team collaboration features.
                                    </p>
                                </div>
                            </div>

                            <!-- Storage Backend Actions -->
                            <div class="flex flex-wrap gap-3 pt-2 border-t border-gray-200 dark:border-gray-600">
                                <button type="button" onclick="testStorageBackend()" 
                                        class="bg-blue-600 text-white px-3 py-2 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors text-sm">
                                    <i class="fas fa-plug mr-1"></i> Test Connection
                                </button>
                                <button type="button" onclick="showStorageMigrationModal()" 
                                        class="bg-yellow-600 text-white px-3 py-2 rounded-md hover:bg-yellow-700 focus:outline-none focus:ring-2 focus:ring-yellow-500 focus:ring-offset-2 transition-colors text-sm">
                                    <i class="fas fa-exchange-alt mr-1"></i> Migrate Certificates
                                </button>
                                <div class="text-xs text-gray-500 dark:text-gray-400 flex items-center">
                                    <i class="fas fa-info-circle mr-1"></i>
                                    Test connection before saving settings
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- DNS Provider Test Connection -->
                    <div id="testConnectionResult" class="mt-4 hidden">
                        <div class="p-4 rounded-md text-sm" id="testConnectionMessage">
                            <!-- Test connection message will be displayed here -->
                        </div>
                    </div>

                    <!-- Submit Button -->
                    <div class="flex justify-end">
                        <button type="submit" id="saveBtn" class="bg-primary text-white px-6 py-2 rounded-md hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2 dark:focus:ring-offset-gray-800 transition-colors">
                            <i class="fas fa-save mr-2"></i>
                            Save Settings
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Backup & Restore Section -->
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 p-6 mt-6">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-lg font-semibold text-gray-900 dark:text-white flex items-center">
                    <i class="fas fa-database mr-2 text-blue-500"></i>
                    Backup & Restore
                </h3>
                <span class="text-xs bg-blue-100 dark:bg-blue-900/30 text-blue-800 dark:text-blue-300 px-2 py-1 rounded-full">
                    Data Protection
                </span>
            </div>
            
            <p class="text-gray-600 dark:text-gray-400 text-sm mb-6">
                Create backups of your settings and certificates to prevent data loss. Restore from previous backups when needed.
            </p>

            <!-- Create Backup Section -->
            <div class="grid md:grid-cols-2 gap-6 mb-6">
                <div class="bg-gray-50 dark:bg-gray-700/50 rounded-lg p-4">
                    <h4 class="font-medium text-gray-900 dark:text-white mb-3 flex items-center">
                        <i class="fas fa-plus-circle mr-2 text-green-500"></i>
                        Create Backup
                    </h4>
                    <p class="text-sm text-gray-600 dark:text-gray-400 mb-4">
                        Create atomic backups that include both settings and certificates to ensure data consistency.
                    </p>
                    <div class="space-y-3">
                        <button type="button" onclick="createBackup('unified', this)" 
                                class="w-full bg-green-600 text-white px-4 py-2 rounded-md hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 transition-colors text-sm">
                            <i class="fas fa-archive mr-2"></i>
                            Create Unified Backup (Recommended)
                        </button>
                    </div>
                </div>

                <div class="bg-gray-50 dark:bg-gray-700/50 rounded-lg p-4">
                    <h4 class="font-medium text-gray-900 dark:text-white mb-3 flex items-center">
                        <i class="fas fa-info-circle mr-2 text-blue-500"></i>
                        Backup Information
                    </h4>
                    <div class="space-y-2 text-sm text-gray-600 dark:text-gray-400">
                        <div class="flex items-start">
                            <i class="fas fa-check text-green-500 mr-2 mt-0.5 text-xs"></i>
                            <span><strong>Unified Backup:</strong> Atomic backup of both settings and certificates ensuring data consistency and preventing configuration mismatches</span>
                        </div>
                        <div class="flex items-start mt-3 pt-2 border-t border-gray-200 dark:border-gray-600">
                            <i class="fas fa-shield-alt text-yellow-500 mr-2 mt-0.5 text-xs"></i>
                            <span class="text-xs">Backups contain sensitive data. Keep them secure and stored safely.</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Existing Backups Section -->
            <div class="border-t border-gray-200 dark:border-gray-600 pt-6">
                <div class="flex items-center justify-between mb-4">
                    <h4 class="font-medium text-gray-900 dark:text-white flex items-center">
                        <i class="fas fa-history mr-2 text-orange-500"></i>
                        Existing Backups
                    </h4>
                    <button type="button" onclick="refreshBackupList()" 
                            class="text-sm text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300">
                        <i class="fas fa-sync-alt mr-1"></i>
                        Refresh
                    </button>
                </div>

                <!-- Backup Lists -->
                <div class="space-y-6">
                    <!-- Unified Backups (Recommended) -->
                    <div>
                        <h5 class="text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
                            <i class="fas fa-archive mr-1 text-green-500"></i>
                            Unified Backups (Recommended)
                            <span class="text-xs bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-300 px-2 py-1 rounded-full ml-2">Atomic</span>
                        </h5>
                        <div id="unified-backup-list" class="space-y-2 max-h-64 overflow-y-auto">
                            <div class="text-sm text-gray-500 dark:text-gray-400 text-center py-4">
                                Loading unified backups...
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Status Messages -->
        <div id="statusMessage" class="mt-4 hidden"></div>
    </div>

    <!-- Add Account Modal -->
    <div id="addAccountModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50 hidden">
        <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white dark:bg-gray-800">
            <div class="mt-3">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-medium text-gray-900 dark:text-white" id="modal-title">
                        Add Account
                    </h3>
                    <button type="button" onclick="closeAddAccountModal()" class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <form id="addAccountForm" class="space-y-4">
                    <div>
                        <label for="account-name" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                            Account Name *
                        </label>
                        <input type="text" id="account-name" name="name" required
                               class="mt-1 block w-full border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary"
                               placeholder="e.g., Production, Development, Client-A">
                    </div>
                    
                    <div>
                        <label for="account-description" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                            Description (optional)
                        </label>
                        <input type="text" id="account-description" name="description"
                               class="mt-1 block w-full border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary"
                               placeholder="Brief description of this account">
                    </div>
                    
                    <!-- Dynamic fields will be populated here based on provider -->
                    <div id="modal-provider-fields"></div>
                    
                    <div class="flex items-center">
                        <input type="checkbox" id="set-as-default" name="set_as_default" 
                               class="h-4 w-4 text-primary focus:ring-primary border-gray-300 rounded">
                        <label for="set-as-default" class="ml-2 block text-sm text-gray-700 dark:text-gray-300">
                            Set as default account
                        </label>
                    </div>
                    
                    <div class="flex justify-end space-x-3 pt-4">
                        <button type="button" onclick="closeAddAccountModal()" 
                                class="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-md text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700">
                            Cancel
                        </button>
                        <button type="button" onclick="saveAccount()" 
                                class="px-4 py-2 bg-primary text-white rounded-md hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                            Add Account
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Edit Account Modal -->
    <div id="editAccountModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50 hidden">
        <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white dark:bg-gray-800">
            <div class="mt-3">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-medium text-gray-900 dark:text-white">
                        Edit Account
                    </h3>
                    <button type="button" onclick="closeEditAccountModal()" class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <form id="editAccountForm" class="space-y-4">
                    <input type="hidden" id="edit-account-id" name="edit-account-id">
                    <input type="hidden" id="edit-provider-name" name="edit-provider-name">
                    
                    <div>
                        <label for="edit-account-name" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                            Account Name *
                        </label>
                        <input type="text" id="edit-account-name" name="name" required
                               class="mt-1 block w-full border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary">
                    </div>
                    
                    <div>
                        <label for="edit-account-description" class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                            Description (optional)
                        </label>
                        <input type="text" id="edit-account-description" name="description"
                               class="mt-1 block w-full border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary">
                    </div>
                    
                    <!-- Dynamic fields will be populated here based on provider -->
                    <div id="edit-modal-provider-fields"></div>
                    
                    <div class="flex items-center">
                        <input type="checkbox" id="edit-set-as-default" name="set_as_default" 
                               class="h-4 w-4 text-primary focus:ring-primary border-gray-300 rounded">
                        <label for="edit-set-as-default" class="ml-2 block text-sm text-gray-700 dark:text-gray-300">
                            Set as default account
                        </label>
                    </div>
                    
                    <div class="flex justify-end space-x-3 pt-4">
                        <button type="button" onclick="closeEditAccountModal()" 
                                class="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-md text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700">
                            Cancel
                        </button>
                        <button type="button" onclick="saveEditAccount()" 
                                class="px-4 py-2 bg-primary text-white rounded-md hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                            Update Account
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Debug Console -->
    <div id="debugConsole" class="fixed bottom-4 left-4 right-4 bg-black text-green-400 font-mono text-xs rounded-lg shadow-lg border border-gray-600 hidden z-40">
        <div class="flex justify-between items-center px-3 py-2 border-b border-gray-700">
            <span class="text-white font-semibold">Settings Debug Console</span>
            <button onclick="clearDebugConsole()" class="text-yellow-400 hover:text-yellow-300" title="Clear console">
                <i class="fas fa-eraser"></i>
            </button>
            <button onclick="toggleDebugConsole()" class="text-gray-400 hover:text-white ml-2" title="Close console">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <div id="debugOutput" class="p-3 max-h-64 overflow-y-auto">
            <div class="text-gray-500">Debug console ready. All settings actions will be logged here...</div>
        </div>
    </div>
    <button onclick="toggleDebugConsole()" class="fixed bottom-4 right-4 bg-gray-800 text-white px-3 py-2 rounded-full shadow-lg z-50 hover:bg-primary">
        <i class="fas fa-bug"></i> Debug
    </button>
    <script>
        // API Configuration
        const API_TOKEN = '{{ api_token }}' || '';
        
        if (!API_TOKEN) {
            console.warn('No API token available - some features may not work');
        }
        
        const API_HEADERS = {
            'Authorization': `Bearer ${API_TOKEN}`,
            'Content-Type': 'application/json'
        };

        // Global variables - properly initialized
        let currentSettings = {};
        let dnsProviders = {};
        let isLoading = false;

        // DOM Elements
        const form = document.getElementById('settingsForm');
        const saveBtn = document.getElementById('saveBtn');
        const statusMessage = document.getElementById('statusMessage');

        // Debug console functions
        function toggleDebugConsole() {
            const consoleDiv = document.getElementById('debugConsole');
            if (consoleDiv.classList.contains('hidden')) {
                consoleDiv.classList.remove('hidden');
            } else {
                consoleDiv.classList.add('hidden');
            }
        }
        
        function clearDebugConsole() {
            document.getElementById('debugOutput').innerHTML = '<div class="text-gray-500">Debug console cleared. All settings actions will be logged here...</div>';
        }
        
        function addDebugLog(message, type = 'info') {
            const output = document.getElementById('debugOutput');
            const color = type === 'error' ? 'text-red-400' : type === 'warn' ? 'text-yellow-400' : 'text-green-400';
            const time = new Date().toLocaleTimeString();
            output.innerHTML += `<div class="${color}">[${time}] ${type.toUpperCase()}: ${message}</div>`;
            output.scrollTop = output.scrollHeight;
        }

        // Message display function
        function showMessage(message, type = 'info') {
            console.log(`${type.toUpperCase()}: ${message}`);
            addDebugLog(message, type);
            
            if (statusMessage) {
                statusMessage.textContent = message;
                statusMessage.className = `mt-4 p-3 rounded-md text-sm ${
                    type === 'success' ? 'bg-green-100 text-green-700 border border-green-200 dark:bg-green-900/20 dark:text-green-400 dark:border-green-600' :
                    type === 'error' ? 'bg-red-100 text-red-700 border border-red-200 dark:bg-red-900/20 dark:text-red-400 dark:border-red-600' :
                    type === 'warning' ? 'bg-yellow-100 text-yellow-700 border border-yellow-200 dark:bg-yellow-900/20 dark:text-yellow-400 dark:border-yellow-600' :
                    'bg-blue-100 text-blue-700 border border-blue-200 dark:bg-blue-900/20 dark:text-blue-400 dark:border-blue-600'
                }`;
                statusMessage.classList.remove('hidden');
                
                // Auto-hide success messages after 5 seconds
                if (type === 'success') {
                    setTimeout(() => {
                        if (statusMessage) {
                            statusMessage.classList.add('hidden');
                        }
                    }, 5000);
                }
            }
        }

        // DNS provider configuration functions
        function showDNSConfig(provider) {
            // Hide all DNS config sections
            document.querySelectorAll('.dns-config').forEach(config => {
                config.classList.add('hidden');
            });
            
            // Show the selected provider's config
            const configSection = document.getElementById(`${provider}-config`);
            if (configSection) {
                configSection.classList.remove('hidden');
                addDebugLog(`Showing DNS config for ${provider}`, 'info');
            } else {
                addDebugLog(`No config section found for ${provider}`, 'warn');
            }
        }

        // Add event listeners for DNS provider selection
        document.addEventListener('DOMContentLoaded', function() {
            addDebugLog('DOM loaded, initializing settings page', 'info');
            
            // Add radio button listeners
            document.querySelectorAll('input[name="dns_provider"]').forEach(radio => {
                radio.addEventListener('change', function() {
                    if (this.checked) {
                        showDNSConfig(this.value);
                        addDebugLog(`DNS provider changed to: ${this.value}`, 'info');
                    }
                });
            });

            // Load settings on page load
            loadSettings();
            
            // Initialize CA provider configuration visibility
            toggleCAProviderConfig();
            
            // Refresh cache stats on load
            refreshCacheStats();
        });

        // Add debug logs to form actions
        if (form) {
            form.addEventListener('submit', function(e) {
                e.preventDefault();
                addDebugLog('Settings form submitted', 'info');
                saveSettings();
            });
        }

        // Save main settings function
        async function saveSettings() {
            try {
                if (isLoading) return;
                isLoading = true;
                
                if (saveBtn) {
                    saveBtn.disabled = true;
                    saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Saving...';
                }
                
                addDebugLog('Saving main settings...', 'info');
                
                const formData = new FormData(form);
                const settings = {
                    email: formData.get('email')?.trim(),
                    domains: formData.get('domains')?.split('\n').map(d => d.trim()).filter(d => d),
                    auto_renew: formData.get('auto_renew') === 'on',
                    renewal_threshold_days: parseInt(formData.get('renewal_threshold_days')) || 30,
                    dns_provider: formData.get('dns_provider'),
                    api_bearer_token: formData.get('api_bearer_token')?.trim(),
                    cache_ttl: parseInt(formData.get('cache_ttl')) || 300,
                    storage_backend: formData.get('storage_backend'),
                    certificate_storage: collectStorageBackendSettings(),
                    default_ca: formData.get('default_ca') || 'letsencrypt',
                    ca_providers: collectCAProviderSettings()
                };
                
                // Validate required fields
                if (!settings.email) {
                    throw new Error('Email address is required');
                }
                
                if (!settings.dns_provider) {
                    throw new Error('DNS provider must be selected');
                }
                
                if (!settings.api_bearer_token) {
                    throw new Error('API Bearer Token is required');
                }
                
                // Add legacy DNS provider configurations from form fields
                const legacyConfig = {};
                
                // Get legacy fields for the selected provider
                const provider = settings.dns_provider;
                const legacyFields = getLegacyFieldsForProvider(provider);
                
                legacyFields.forEach(fieldName => {
                    const value = formData.get(fieldName);
                    if (value && value.trim()) {
                        const configKey = fieldName.replace(`${provider}_`, '');
                        legacyConfig[configKey] = value.trim();
                    }
                });
                
                // Only include legacy config if we have some values and no multi-account data
                if (Object.keys(legacyConfig).length > 0) {
                    if (!settings.dns_providers) settings.dns_providers = {};
                    if (!settings.dns_providers[provider]) settings.dns_providers[provider] = {};
                    
                    // Check if we already have multi-account data
                    const hasMultiAccount = Object.values(settings.dns_providers[provider]).some(val => 
                        typeof val === 'object' && val.name
                    );
                    
                    if (!hasMultiAccount) {
                        Object.assign(settings.dns_providers[provider], legacyConfig);
                    }
                }
                
                addDebugLog(`Settings to save: ${JSON.stringify(settings, null, 2)}`, 'info');
                
                const response = await fetch('/api/web/settings', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(settings)
                });
                
                if (!response.ok) {
                    const errorData = await response.text();
                    throw new Error(`HTTP ${response.status}: ${errorData}`);
                }
                
                const result = await response.json();
                addDebugLog('Settings saved successfully', 'info');
                showMessage('Settings saved successfully', 'success');
                
                // Reload settings to refresh the UI
                await loadSettings();
                
            } catch (error) {
                addDebugLog(`Error saving settings: ${error.message}`, 'error');
                showMessage(`Error saving settings: ${error.message}`, 'error');
            } finally {
                isLoading = false;
                if (saveBtn) {
                    saveBtn.disabled = false;
                    saveBtn.innerHTML = '<i class="fas fa-save mr-2"></i>Save Settings';
                }
            }
        }

        function getLegacyFieldsForProvider(provider) {
            const fieldMappings = {
                'cloudflare': ['cloudflare_api_token'],
                'route53': ['route53_access_key_id', 'route53_secret_access_key', 'route53_region'],
                'azure': ['azure_subscription_id', 'azure_resource_group', 'azure_tenant_id', 'azure_client_id', 'azure_client_secret'],
                'google': ['google_project_id', 'google_service_account_key'],
                'powerdns': ['powerdns_api_url', 'powerdns_api_key'],
                'digitalocean': ['digitalocean_api_token'],
                'linode': ['linode_api_key'],
                'gandi': ['gandi_api_token'],
                'ovh': ['ovh_endpoint', 'ovh_application_key', 'ovh_application_secret', 'ovh_consumer_key'],
                'namecheap': ['namecheap_username', 'namecheap_api_key'],
                'rfc2136': ['rfc2136_nameserver', 'rfc2136_tsig_key', 'rfc2136_tsig_secret', 'rfc2136_tsig_algorithm'],
                'hetzner': ['hetzner_api_token'],
                'porkbun': ['porkbun_api_key', 'porkbun_secret_key'],
                'godaddy': ['godaddy_api_key', 'godaddy_secret'],
                'he-ddns': ['he_ddns_username', 'he_ddns_password'],
                'dynudns': ['dynudns_token'],
                'dnsmadeeasy': ['dnsmadeeasy_api_key', 'dnsmadeeasy_secret_key'],
                'nsone': ['nsone_api_key']
            };
            
            return fieldMappings[provider] || [];
        }
    
        // Cache management functions
        async function refreshCacheStats() {
            try {
                addDebugLog('Refreshing cache stats...', 'info');
                
                const response = await fetch('/api/web/cache/stats');
                if (response.ok) {
                    const stats = await response.json();
                    
                    const entriesEl = document.getElementById('cache-entries');
                    const ttlEl = document.getElementById('cache-current-ttl');
                    
                    if (entriesEl) entriesEl.textContent = stats.entries || 0;
                    if (ttlEl) ttlEl.textContent = `${stats.current_ttl || 300}s`;
                    
                    addDebugLog(`Cache stats refreshed: ${stats.entries} entries, ${stats.current_ttl}s TTL`, 'info');
                } else {
                    addDebugLog('Failed to refresh cache stats', 'warn');
                }
            } catch (error) {
                addDebugLog(`Error refreshing cache stats: ${error.message}`, 'error');
            }
        }
        
        async function clearDeploymentCache() {
            try {
                addDebugLog('Clearing deployment cache...', 'info');
                
                const response = await fetch('/api/web/cache/clear', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                if (response.ok) {
                    const result = await response.json();
                    addDebugLog('Cache cleared successfully', 'info');
                    showMessage('Cache cleared successfully', 'success');
                    await refreshCacheStats();
                } else {
                    addDebugLog('Failed to clear cache', 'warn');
                    showMessage('Failed to clear cache', 'error');
                }
            } catch (error) {
                addDebugLog(`Error clearing cache: ${error.message}`, 'error');
                showMessage('Error clearing cache', 'error');
            }
        }

        // Load settings on page load
        async function loadSettings(suppressErrorMessages = false) {
            try {
                addDebugLog('Loading settings from backend...', 'info');
                
                const response = await fetch('/api/web/settings', {
                    method: 'GET',
                    headers: API_HEADERS
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const settings = await response.json();
                addDebugLog(`Settings loaded: ${Object.keys(settings).join(', ')}`, 'info');
                
                currentSettings = settings;
                populateForm(settings);
                
                // Load DNS provider configurations and status
                await loadDNSProviders();
                
                addDebugLog('Settings loaded and form populated successfully', 'info');
                
            } catch (error) {
                addDebugLog(`Failed to load settings: ${error.message}`, 'error');
                console.error('Error loading settings:', error);
                if (!suppressErrorMessages) {
                    showMessage(`Failed to load settings: ${error.message}`, 'error');
                }
                throw error; // Re-throw so caller can handle it
            }
        }
        
        // Load DNS provider configurations and account info
        async function loadDNSProviders() {
            try {
                addDebugLog('Loading DNS provider configurations...', 'info');
                dnsProviders = {};
                
                // Load provider configurations from current settings
                if (currentSettings && currentSettings.dns_providers) {
                    for (const [provider, config] of Object.entries(currentSettings.dns_providers)) {
                        try {
                            dnsProviders[provider] = {
                                configured: false,
                                accounts: []
                            };
                            
                            if (config && typeof config === 'object') {
                                // Check if this is multi-account format
                                if (Object.values(config).some(val => typeof val === 'object' && 'name' in val)) {
                                    // Multi-account format
                                    for (const [accountId, accountConfig] of Object.entries(config)) {
                                        if (typeof accountConfig === 'object' && accountConfig.name) {
                                            dnsProviders[provider].accounts.push({
                                                id: accountId,
                                                name: accountConfig.name,
                                                description: accountConfig.description || '',
                                                ...accountConfig
                                            });
                                        }
                                    }
                                    dnsProviders[provider].configured = dnsProviders[provider].accounts.length > 0;
                                } else {
                                    // Legacy single-account format
                                    const hasCredentials = Object.values(config).some(val => val && val.trim && val.trim().length > 0);
                                    dnsProviders[provider].configured = hasCredentials;
                                    
                                    if (hasCredentials) {
                                        dnsProviders[provider].accounts.push({
                                            id: 'default',
                                            name: 'Default Account',
                                            description: 'Legacy configuration',
                                            ...config
                                        });
                                    }
                                }
                            }
                            
                            addDebugLog(`${provider}: ${dnsProviders[provider].configured ? 'configured' : 'not configured'} (${dnsProviders[provider].accounts.length} accounts)`, 'info');
                            
                        } catch (error) {
                            addDebugLog(`Error processing ${provider}: ${error.message}`, 'warn');
                        }
                    }
                }
                
                // Update provider status indicators
                updateProviderStatusIndicators();
                
                // Update account lists in DNS config sections
                updateAccountLists();
                
                addDebugLog('DNS provider configurations loaded', 'info');
                
            } catch (error) {
                addDebugLog(`Failed to load DNS providers: ${error.message}`, 'error');
                console.error('Error loading DNS providers:', error);
            }
        }
        
        // Update DNS provider status indicators in the UI
        function updateProviderStatusIndicators() {
            const providers = [
                'cloudflare', 'route53', 'azure', 'google', 'powerdns', 
                'digitalocean', 'linode', 'gandi', 'ovh', 'namecheap',
                'vultr', 'dnsmadeeasy', 'nsone', 'rfc2136', 'hetzner',
                'porkbun', 'godaddy', 'he-ddns', 'dynudns'
            ];
            
            providers.forEach(provider => {
                const statusEl = document.getElementById(`${provider}-status`);
                const accountsEl = document.getElementById(`${provider}-accounts`);
                const countEl = document.getElementById(`${provider}-account-count`);
                
                if (statusEl) {
                    const providerData = dnsProviders[provider];
                    if (providerData && providerData.configured) {
                        statusEl.textContent = 'Configured';
                        statusEl.className = 'text-xs text-green-600 dark:text-green-400 mt-1';
                        
                        if (accountsEl && countEl) {
                            countEl.textContent = providerData.accounts.length;
                            accountsEl.classList.remove('hidden');
                        }
                    } else {
                        statusEl.textContent = 'Not configured';
                        statusEl.className = 'text-xs text-gray-500 dark:text-gray-400 mt-1';
                        
                        if (accountsEl) {
                            accountsEl.classList.add('hidden');
                        }
                    }
                }
            });
        }

        // Fix form validation function
        function validateDNSProvider(provider) {
            const providerData = dnsProviders[provider];
            if (!providerData) return false;
            
            // Check if provider has at least one configured account
            return providerData.configured && providerData.accounts.length > 0;
        }

        // Form population function
        function populateForm(data) {
            try {
                addDebugLog('Populating form with settings data...', 'info');
                
                // Basic settings
                if (data.email) {
                    const emailField = document.getElementById('email');
                    if (emailField) {
                        emailField.value = data.email;
                        addDebugLog('Email field populated', 'info');
                    }
                }
                
                if (data.domains && Array.isArray(data.domains)) {
                    const domainsField = document.getElementById('domains');
                    if (domainsField) {
                        // Handle both string and object formats
                        const domainStrings = data.domains.map(d => 
                            typeof d === 'string' ? d : (d.domain || '')
                        ).filter(d => d);
                        domainsField.value = domainStrings.join('\n');
                        addDebugLog(`Domains field populated with ${domainStrings.length} domains`, 'info');
                    }
                }
                
                if (data.auto_renew !== undefined) {
                    const autoRenewField = document.getElementById('auto_renew');
                    if (autoRenewField) {
                        autoRenewField.checked = data.auto_renew;
                        addDebugLog(`Auto-renewal set to ${data.auto_renew}`, 'info');
                    }
                }
                
                if (data.renewal_threshold_days !== undefined) {
                    const thresholdField = document.getElementById('renewal_threshold_days');
                    if (thresholdField) {
                        thresholdField.value = data.renewal_threshold_days;
                        addDebugLog(`Renewal threshold set to ${data.renewal_threshold_days} days`, 'info');
                    }
                }
                
                if (data.api_bearer_token) {
                    const tokenField = document.getElementById('api_bearer_token');
                    if (tokenField) {
                        tokenField.value = data.api_bearer_token;
                        addDebugLog('API bearer token field populated', 'info');
                    }
                }
                
                if (data.cache_ttl) {
                    const cacheField = document.getElementById('cache_ttl');
                    if (cacheField) {
                        cacheField.value = data.cache_ttl;
                        addDebugLog(`Cache TTL set to ${data.cache_ttl}`, 'info');
                    }
                }
                
                // DNS provider selection
                if (data.dns_provider) {
                    const providerRadio = document.querySelector(`input[name="dns_provider"][value="${data.dns_provider}"]`);
                    if (providerRadio) {
                        providerRadio.checked = true;
                        showDNSConfig(data.dns_provider);
                        addDebugLog(`DNS provider set to ${data.dns_provider}`, 'info');
                    }
                }
                
                // DNS provider configurations (legacy fields)
                const dnsProviders = data.dns_providers || {};
                for (const [provider, config] of Object.entries(dnsProviders)) {
                    if (typeof config === 'object' && config !== null) {
                        // Check if this is old single-account format
                        if (config.api_token || config.access_key_id || config.api_key) {
                            populateLegacyProviderFields(provider, config);
                        }
                    }
                }
                
                // Load storage backend settings
                loadStorageBackendSettings(data);
                addDebugLog('Storage backend settings loaded', 'info');
                
                // Load CA provider settings
                loadCAProviderSettings(data);
                addDebugLog('CA provider settings loaded', 'info');
                
                addDebugLog('Form populated successfully', 'info');
            } catch (error) {
                addDebugLog(`Error populating form: ${error.message}`, 'error');
                console.error('Error populating form:', error);
            }
        }
        
        // Legacy provider field population
        function populateLegacyProviderFields(provider, config) {
            try {
                addDebugLog(`Populating legacy fields for ${provider}`, 'info');
                
                const fieldMappings = {
                    'cloudflare': [
                        { field: 'cloudflare_api_token', config: 'api_token' }
                    ],
                    'route53': [
                        { field: 'route53_access_key_id', config: 'access_key_id' },
                        { field: 'route53_secret_access_key', config: 'secret_access_key' },
                        { field: 'route53_region', config: 'region' }
                    ],
                    'digitalocean': [
                        { field: 'digitalocean_api_token', config: 'api_token' }
                    ],
                    'azure': [
                        { field: 'azure_subscription_id', config: 'subscription_id' },
                        { field: 'azure_resource_group', config: 'resource_group' },
                        { field: 'azure_tenant_id', config: 'tenant_id' },
                        { field: 'azure_client_id', config: 'client_id' },
                        { field: 'azure_client_secret', config: 'client_secret' }
                    ],
                    'google': [
                        { field: 'google_project_id', config: 'project_id' },
                        { field: 'google_service_account_key', config: 'service_account_key' }
                    ],
                    'powerdns': [
                        { field: 'powerdns_api_url', config: 'api_url' },
                        { field: 'powerdns_api_key', config: 'api_key' }
                    ]
                };
                
                const mappings = fieldMappings[provider] || [];
                mappings.forEach(mapping => {
                    const field = document.getElementById(mapping.field);
                    if (field && config[mapping.config]) {
                        field.value = config[mapping.config];
                        addDebugLog(`Field ${mapping.field} populated`, 'info');
                    }
                });
            } catch (error) {
                addDebugLog(`Error populating legacy fields for ${provider}: ${error.message}`, 'warn');
            }
        }
        
        // Modal management functions
        function showAddAccountModal(provider) {
            addDebugLog(`Opening add account modal for ${provider}`, 'info');
            
            const modal = document.getElementById('addAccountModal');
            const modalTitle = document.getElementById('modal-title');
            const providerFields = document.getElementById('modal-provider-fields');
            const accountNameField = document.getElementById('account-name');
            const accountDescField = document.getElementById('account-description');
            const setDefaultCheckbox = document.getElementById('set-as-default');
            
            if (!modal || !modalTitle || !providerFields) {
                addDebugLog('Modal elements not found', 'error');
                return;
            }
            
            // Set modal title
            const providerNames = {
                'cloudflare': 'Cloudflare',
                'route53': 'AWS Route53',
                'azure': 'Azure DNS',
                'google': 'Google Cloud DNS',
                'powerdns': 'PowerDNS',
                'digitalocean': 'DigitalOcean',
                'linode': 'Linode',
                'gandi': 'Gandi',
                'ovh': 'OVH',
                'namecheap': 'Namecheap',
                'rfc2136': 'RFC2136',
                'hetzner': 'Hetzner',
                'porkbun': 'Porkbun',
                'godaddy': 'GoDaddy',
                'he-ddns': 'Hurricane Electric',
                'dynudns': 'Dynu',
                'dnsmadeeasy': 'DNS Made Easy',
                'nsone': 'NS1'
            };
            modalTitle.textContent = `Add ${providerNames[provider] || provider} Account`;
            
            // Clear previous fields
            providerFields.innerHTML = '';
            if (accountNameField) accountNameField.value = '';
            if (accountDescField) accountDescField.value = '';
            if (setDefaultCheckbox) setDefaultCheckbox.checked = false;
            
            // Generate provider-specific fields
            const fields = getProviderFields(provider);
            providerFields.innerHTML = fields;
            
            // Store current provider
            modal.dataset.provider = provider;
            
            // Show modal
            modal.classList.remove('hidden');
            document.body.style.overflow = 'hidden';
        }

        function closeAddAccountModal() {
            const modal = document.getElementById('addAccountModal');
            if (modal) {
                modal.classList.add('hidden');
                document.body.style.overflow = '';
                
                // Clear form
                document.getElementById('addAccountForm').reset();
                document.getElementById('modal-provider-fields').innerHTML = '';
            }
        }

        function showEditAccountModal(provider, accountId) {
            addDebugLog(`Opening edit account modal for ${provider}:${accountId}`, 'info');
            
            const modal = document.getElementById('editAccountModal');
            const editAccountIdField = document.getElementById('edit-account-id');
            const editProviderField = document.getElementById('edit-provider-name');
            const editProviderFields = document.getElementById('edit-modal-provider-fields');
            const editAccountNameField = document.getElementById('edit-account-name');
            const editAccountDescField = document.getElementById('edit-account-description');
            const editSetDefaultCheckbox = document.getElementById('edit-set-as-default');
            
            if (!modal || !editAccountIdField || !editProviderField) {
                addDebugLog('Edit modal elements not found', 'error');
                return;
            }
            
            // Set hidden fields
            editAccountIdField.value = accountId;
            editProviderField.value = provider;
            
            // Get account data
            const providerData = dnsProviders[provider];
            const account = providerData?.accounts.find(acc => acc.id === accountId);
            
            if (!account) {
                addDebugLog(`Account ${accountId} not found for provider ${provider}`, 'error');
                showMessage('Account not found', 'error');
                return;
            }
            
            // Populate basic fields
            if (editAccountNameField) editAccountNameField.value = account.name || '';
            if (editAccountDescField) editAccountDescField.value = account.description || '';
            if (editSetDefaultCheckbox) {
                editSetDefaultCheckbox.checked = currentSettings.default_accounts?.[provider] === accountId;
            }
            
            // Generate provider-specific fields with current values
            const fields = getProviderFields(provider, account);
            editProviderFields.innerHTML = fields;
            
            // Show modal
            modal.classList.remove('hidden');
            document.body.style.overflow = 'hidden';
        }

        function closeEditAccountModal() {
            const modal = document.getElementById('editAccountModal');
            if (modal) {
                modal.classList.add('hidden');
                document.body.style.overflow = '';
                
                // Clear form
                document.getElementById('editAccountForm').reset();
                document.getElementById('edit-modal-provider-fields').innerHTML = '';
            }
        }

        function getProviderFields(provider, existingData = {}) {
            const fieldMappings = {
                'cloudflare': [
                    { name: 'api_token', label: 'API Token', type: 'password', placeholder: 'Enter your Cloudflare API token', required: true }
                ],
                'route53': [
                    { name: 'access_key_id', label: 'Access Key ID', type: 'password', placeholder: 'AKIAIOSFODNN7EXAMPLE', required: true },
                    { name: 'secret_access_key', label: 'Secret Access Key', type: 'password', placeholder: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY', required: true },
                    { name: 'region', label: 'Region', type: 'text', placeholder: 'us-east-1', defaultValue: 'us-east-1', required: false }
                ],
                'azure': [
                    { name: 'subscription_id', label: 'Subscription ID', type: 'text', placeholder: '12345678-1234-1234-1234-123456789012', required: true },
                    { name: 'resource_group', label: 'Resource Group', type: 'text', placeholder: 'my-dns-resource-group', required: true },
                    { name: 'tenant_id', label: 'Tenant ID', type: 'text', placeholder: '12345678-1234-1234-1234-123456789012', required: true },
                    { name: 'client_id', label: 'Client ID', type: 'text', placeholder: '12345678-1234-1234-1234-123456789012', required: true },
                    { name: 'client_secret', label: 'Client Secret', type: 'password', placeholder: 'Your Azure client secret', required: true }
                ],
                'google': [
                    { name: 'project_id', label: 'Project ID', type: 'text', placeholder: 'my-gcp-project-123456', required: true },
                    { name: 'service_account_key', label: 'Service Account JSON Key', type: 'textarea', placeholder: '{"type": "service_account", "project_id": "...", ...}', required: true }
                ],
                'powerdns': [
                    { name: 'api_url', label: 'API URL', type: 'url', placeholder: 'https://powerdns.example.com:8081', required: true },
                    { name: 'api_key', label: 'API Key', type: 'password', placeholder: 'Your PowerDNS API key', required: true }
                ],
                'digitalocean': [
                    { name: 'api_token', label: 'API Token', type: 'password', placeholder: 'Your DigitalOcean API token', required: true }
                ],
                'linode': [
                    { name: 'api_key', label: 'API Key', type: 'password', placeholder: 'Your Linode API key', required: true }
                ],
                'gandi': [
                    { name: 'api_token', label: 'API Token', type: 'password', placeholder: 'Your Gandi LiveDNS API token', required: true }
                ],
                'ovh': [
                    { name: 'endpoint', label: 'Endpoint', type: 'select', options: [
                        { value: 'ovh-eu', label: 'ovh-eu (Europe)' },
                        { value: 'ovh-us', label: 'ovh-us (US)' },
                        { value: 'ovh-ca', label: 'ovh-ca (Canada)' },
                        { value: 'kimsufi-eu', label: 'kimsufi-eu' },
                        { value: 'kimsufi-ca', label: 'kimsufi-ca' },
                        { value: 'soyoustart-eu', label: 'soyoustart-eu' },
                        { value: 'soyoustart-ca', label: 'soyoustart-ca' }
                    ], required: true },
                    { name: 'application_key', label: 'Application Key', type: 'password', placeholder: 'Your application key', required: true },
                    { name: 'application_secret', label: 'Application Secret', type: 'password', placeholder: 'Your application secret', required: true },
                    { name: 'consumer_key', label: 'Consumer Key', type: 'password', placeholder: 'Your consumer key', required: true }
                ],
                'namecheap': [
                    { name: 'username', label: 'Username', type: 'text', placeholder: 'Your Namecheap username', required: true },
                    { name: 'api_key', label: 'API Key', type: 'password', placeholder: 'Your Namecheap API key', required: true }
                ],
                'rfc2136': [
                    { name: 'nameserver', label: 'Nameserver', type: 'text', placeholder: 'ns.example.com', required: true },
                    { name: 'tsig_key', label: 'TSIG Key Name', type: 'text', placeholder: 'mykey', required: true },
                    { name: 'tsig_secret', label: 'TSIG Secret', type: 'password', placeholder: 'Base64-encoded secret', required: true },
                    { name: 'tsig_algorithm', label: 'TSIG Algorithm', type: 'select', options: [
                        { value: 'HMAC-MD5', label: 'HMAC-MD5' },
                        { value: 'HMAC-SHA1', label: 'HMAC-SHA1' },
                        { value: 'HMAC-SHA224', label: 'HMAC-SHA224' },
                        { value: 'HMAC-SHA256', label: 'HMAC-SHA256' },
                        { value: 'HMAC-SHA384', label: 'HMAC-SHA384' },
                        { value: 'HMAC-SHA512', label: 'HMAC-SHA512' }
                    ], defaultValue: 'HMAC-SHA256', required: false }
                ],
                'hetzner': [
                    { name: 'api_token', label: 'API Token', type: 'password', placeholder: 'Your Hetzner DNS API token', required: true }
                ],
                'porkbun': [
                    { name: 'api_key', label: 'API Key', type: 'password', placeholder: 'Your Porkbun API key', required: true },
                    { name: 'secret_key', label: 'Secret Key', type: 'password', placeholder: 'Your Porkbun secret key', required: true }
                ],
                'godaddy': [
                    { name: 'api_key', label: 'API Key', type: 'password', placeholder: 'Your GoDaddy API key', required: true },
                    { name: 'secret', label: 'API Secret', type: 'password', placeholder: 'Your GoDaddy API secret', required: true }
                ],
                'he-ddns': [
                    { name: 'username', label: 'Username', type: 'text', placeholder: 'Your Hurricane Electric username', required: true },
                    { name: 'password', label: 'Password', type: 'password', placeholder: 'Your Hurricane Electric password', required: true }
                ],
                'dynudns': [
                    { name: 'token', label: 'API Token', type: 'password', placeholder: 'Your Dynu API token', required: true }
                ],
                'dnsmadeeasy': [
                    { name: 'api_token', label: 'API Token', type: 'password', placeholder: 'Your DNS Made Easy API token', required: true }
                ],
                'nsone': [
                    { name: 'api_token', label: 'API Token', type: 'password', placeholder: 'Your NS1 API token', required: true }
                ]
            };
            
            const fields = fieldMappings[provider] || [];
            let html = '';
            
            fields.forEach(field => {
                const value = existingData[field.name] || field.defaultValue || '';
                const fieldId = `modal-${field.name}`;
                
                html += `<div class="mb-4">`;
                html += `<label for="${fieldId}" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">`;
                html += `${field.label}${field.required ? ' *' : ''}`;
                html += `</label>`;
                
                if (field.type === 'select') {
                    html += `<select id="${fieldId}" name="${field.name}" class="mt-1 block w-full border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary" ${field.required ? 'required' : ''}>`;
                    if (!field.required) {
                        html += `<option value="">Select ${field.label.toLowerCase()}</option>`;
                    }
                    field.options.forEach(option => {
                        const selected = value === option.value ? 'selected' : '';
                        html += `<option value="${option.value}" ${selected}>${option.label}</option>`;
                    });
                    html += `</select>`;
                } else if (field.type === 'textarea') {
                    html += `<textarea id="${fieldId}" name="${field.name}" rows="4" class="mt-1 block w-full border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary" placeholder="${field.placeholder}" ${field.required ? 'required' : ''}>${value}</textarea>`;
                } else {
                    html += `<input type="${field.type}" id="${fieldId}" name="${field.name}" class="mt-1 block w-full border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary focus:border-primary" placeholder="${field.placeholder}" value="${value}" ${field.required ? 'required' : ''}>`;
                }
                
                html += `</div>`;
            });
            
            return html;
        }

        async function saveAccount() {
            try {
                addDebugLog('Saving new account...', 'info');
                
                const modal = document.getElementById('addAccountModal');
                const provider = modal.dataset.provider;
                const form = document.getElementById('addAccountForm');
                const formData = new FormData(form);
                
                if (!provider) {
                    throw new Error('Provider not specified');
                }
                
                // Generate a unique account ID
                const accountName = formData.get('name') || 'Untitled Account';
                const accountId = accountName.toLowerCase().replace(/[^a-z0-9]/g, '_').replace(/_+/g, '_').trim('_') || 'account_' + Date.now();
                
                // Build account configuration
                const accountConfig = {
                    name: accountName,
                    description: formData.get('description') || ''
                };
                
                // Add provider-specific fields
                const providerFieldsContainer = document.getElementById('modal-provider-fields');
                const providerFields = providerFieldsContainer.querySelectorAll('input, select, textarea');
                
                providerFields.forEach(field => {
                    if (field.name && field.value) {
                        accountConfig[field.name] = field.value;
                    }
                });
                
                // Check if any required provider fields are empty
                const requiredFields = providerFieldsContainer.querySelectorAll('input[required], select[required], textarea[required]');
                for (const field of requiredFields) {
                    if (!field.value || !field.value.trim()) {
                        throw new Error(`${field.placeholder || field.name} is required`);
                    }
                }
                
                const payload = {
                    account_id: accountId,
                    config: accountConfig,
                    set_as_default: formData.get('set_as_default') === 'on'
                };
                
                addDebugLog(`Account payload: ${JSON.stringify(payload, null, 2)}`, 'info');
                
                // Send to backend
                const response = await fetch(`/api/dns/${provider}/accounts`, {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${API_TOKEN}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(payload)
                });
                
                if (!response.ok) {
                    const errorData = await response.text();
                    throw new Error(`HTTP ${response.status}: ${errorData}`);
                }
                
                const result = await response.json();
                addDebugLog(`Account created: ${result.account_id}`, 'info');
                showMessage(`Account "${accountName}" created successfully`, 'success');
                
                // Refresh settings and close modal
                await loadSettings();
                closeAddAccountModal();
                
            } catch (error) {
                addDebugLog(`Error saving account: ${error.message}`, 'error');
                showMessage(`Error saving account: ${error.message}`, 'error');
            }
        }

        async function saveEditAccount() {
            try {
                addDebugLog('Saving account changes...', 'info');
                
                const form = document.getElementById('editAccountForm');
                const formData = new FormData(form);
                const provider = formData.get('edit-provider-name');
                const accountId = formData.get('edit-account-id');
                
                if (!provider || !accountId) {
                    throw new Error('Provider or account ID not specified');
                }
                
                // Build account data
                const accountData = {
                    name: formData.get('name') || 'Untitled Account',
                    description: formData.get('description') || '',
                    set_as_default: formData.get('set_as_default') === 'on'
                };
                
                // Add provider-specific fields
                const providerFieldsContainer = document.getElementById('edit-modal-provider-fields');
                const providerFields = providerFieldsContainer.querySelectorAll('input, select, textarea');
                
                providerFields.forEach(field => {
                    if (field.name && field.value) {
                        accountData[field.name] = field.value;
                    }
                });
                
                addDebugLog(`Updated account data: ${JSON.stringify(accountData, null, 2)}`, 'info');
                
                // Send to backend
                const response = await fetch(`/api/dns/${provider}/accounts/${accountId}`, {
                    method: 'PUT',
                    headers: {
                        'Authorization': `Bearer ${API_TOKEN}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(accountData)
                });
                
                if (!response.ok) {
                    const errorData = await response.text();
                    throw new Error(`HTTP ${response.status}: ${errorData}`);
                }
                
                const result = await response.json();
                addDebugLog(`Account updated: ${accountId}`, 'info');
                showMessage(`Account "${accountData.name}" updated successfully`, 'success');
                
                // Refresh settings and close modal
                await loadSettings();
                closeEditAccountModal();
                
            } catch (error) {
                addDebugLog(`Error updating account: ${error.message}`, 'error');
                showMessage(`Error updating account: ${error.message}`, 'error');
            }
        }

        async function deleteAccount(provider, accountId) {
            if (!confirm('Are you sure you want to delete this account? This action cannot be undone.')) {
                return;
            }
            
            try {
                addDebugLog(`Deleting account ${provider}:${accountId}`, 'info');
                
                const response = await fetch(`/api/dns/${provider}/accounts/${accountId}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${API_TOKEN}`
                    }
                });
                
                if (!response.ok) {
                    const errorData = await response.text();
                    throw new Error(`HTTP ${response.status}: ${errorData}`);
                }
                
                addDebugLog(`Account deleted: ${accountId}`, 'info');
                showMessage('Account deleted successfully', 'success');
                
                // Refresh settings
                await loadSettings();
                
            } catch (error) {
                addDebugLog(`Error deleting account: ${error.message}`, 'error');
                showMessage(`Error deleting account: ${error.message}`, 'error');
            }
        }

        // Update account lists in the DNS config sections
        function updateAccountLists() {
            const providers = Object.keys(dnsProviders);
            
            providers.forEach(provider => {
                const accountsListContainer = document.getElementById(`${provider}-accounts-list`);
                const legacyConfigContainer = document.getElementById(`${provider}-legacy-config`);
                
                if (!accountsListContainer) return;
                
                const providerData = dnsProviders[provider];
                
                if (providerData && providerData.accounts && providerData.accounts.length > 0) {
                    // Show multi-account interface
                    accountsListContainer.innerHTML = '';
                    
                    providerData.accounts.forEach(account => {
                        const isDefault = currentSettings.default_accounts?.[provider] === account.id;
                        const accountCard = createAccountCard(provider, account, isDefault);
                        accountsListContainer.appendChild(accountCard);
                    });
                    
                    // Hide legacy config if we have multi-account data
                    if (legacyConfigContainer && providerData.accounts.some(acc => acc.id !== 'default')) {
                        legacyConfigContainer.style.display = 'none';
                    }
                } else {
                    // Show legacy config for backward compatibility
                    accountsListContainer.innerHTML = '<div class="text-sm text-gray-500 dark:text-gray-400">No accounts configured yet.</div>';
                    if (legacyConfigContainer) {
                        legacyConfigContainer.style.display = 'block';
                    }
                }
            });
        }

        function createAccountCard(provider, account, isDefault) {
            const card = document.createElement('div');
            card.className = 'bg-white dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded-lg p-4';
            
            card.innerHTML = `
                <div class="flex items-center justify-between">
                    <div class="flex-1">
                        <div class="flex items-center space-x-2">
                            <h5 class="text-sm font-medium text-gray-900 dark:text-white">${account.name}</h5>
                            ${isDefault ? '<span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400"><i class="fas fa-star mr-1"></i>Default</span>' : ''}
                        </div>
                        ${account.description ? `<p class="text-xs text-gray-500 dark:text-gray-400 mt-1">${account.description}</p>` : ''}
                        <div class="text-xs text-gray-400 dark:text-gray-500 mt-1">ID: ${account.id}</div>
                    </div>
                    <div class="flex items-center space-x-2">
                        <button type="button" onclick="showEditAccountModal('${provider}', '${account.id}')" 
                                class="inline-flex items-center px-2 py-1 border border-gray-300 dark:border-gray-600 shadow-sm text-xs font-medium rounded text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-600 hover:bg-gray-50 dark:hover:bg-gray-500 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                            <i class="fas fa-edit mr-1"></i>
                            Edit
                        </button>
                        <button type="button" onclick="deleteAccount('${provider}', '${account.id}')" 
                                class="inline-flex items-center px-2 py-1 border border-red-300 shadow-sm text-xs font-medium rounded text-red-700 bg-white hover:bg-red-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500">
                            <i class="fas fa-trash mr-1"></i>
                            Delete
                        </button>
                    </div>
                </div>
            `;
            
            return card;
        }

        // =============================================
        // BACKUP MANAGEMENT FUNCTIONS
        // =============================================

        async function createBackup(type, buttonElement) {
            let button = null;
            let originalText = '';
            
            try {
                addDebugLog(`Creating ${type} backup...`, 'info');
                
                // Get button element - either passed directly or from event
                button = buttonElement || (window.event && window.event.target);
                originalText = button ? button.innerHTML : '';
                
                if (button) {
                    button.disabled = true;
                    button.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i>Creating...';
                }
                
                // Map legacy backup types to new unified format
                let backupType = type;
                if (type === 'full') {
                    backupType = 'unified';
                }
                
                const response = await fetch('/api/backups/create', {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${API_TOKEN}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        type: backupType,
                        reason: 'manual_backup'
                    })
                });
                
                if (!response.ok) {
                    const errorData = await response.text();
                    throw new Error(`HTTP ${response.status}: ${errorData}`);
                }
                
                const result = await response.json();
                
                if (result.message) {
                    addDebugLog(`Backup created successfully: ${result.backups.map(b => b.filename).join(', ')}`, 'info');
                    
                    let message = `${type === 'unified' ? 'Unified' : type} backup created successfully!`;
                    if (result.recommendation) {
                        message += ` Note: ${result.recommendation}`;
                    }
                    showMessage(message, 'success');
                    
                    // Refresh backup list
                    await refreshBackupList();
                } else {
                    throw new Error(result.error || 'Failed to create backup');
                }
                
            } catch (error) {
                addDebugLog(`Error creating backup: ${error.message}`, 'error');
                showMessage(`Error creating backup: ${error.message}`, 'error');
            } finally {
                // Restore button state
                if (button && originalText) {
                    button.disabled = false;
                    button.innerHTML = originalText;
                }
            }
        }

        async function refreshBackupList() {
            try {
                addDebugLog('Refreshing backup list...', 'info');
                
                const response = await fetch('/api/backups', {
                    method: 'GET',
                    headers: {
                        'Authorization': `Bearer ${API_TOKEN}`,
                        'Content-Type': 'application/json'
                    }
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const backups = await response.json();
                updateBackupList(backups);
                
                addDebugLog(`Backup list refreshed: ${backups.unified.length} backups`, 'info');
                
            } catch (error) {
                addDebugLog(`Error refreshing backup list: ${error.message}`, 'error');
                console.error('Error refreshing backup list:', error);
                
                // Show error in backup list container
                const backupList = document.getElementById('unified-backup-list');
                if (backupList) {
                    backupList.innerHTML = `
                        <div class="p-4 text-center text-red-500 dark:text-red-400">
                            <i class="fas fa-exclamation-triangle mr-2"></i>
                            Error loading backups: ${error.message}
                        </div>
                    `;
                }
            }
        }

        function updateBackupList(backups) {
            const unifiedBackupList = document.getElementById('unified-backup-list');
            
            if (!unifiedBackupList) return;
            
            // Update Unified Backups (only show unified backups)
            if (backups.unified && backups.unified.length === 0) {
                unifiedBackupList.innerHTML = `
                    <div class="p-4 text-center text-gray-500 dark:text-gray-400">
                        <i class="fas fa-archive mr-2"></i>
                        No backups yet
                        <div class="text-xs mt-1">Create your first backup above!</div>
                    </div>
                `;
            } else if (backups.unified) {
                let unifiedHtml = '';
                backups.unified.slice(0, 10).forEach(backup => {
                    const metadata = backup.metadata || {};
                    const createdDate = new Date(metadata.created || metadata.timestamp).toLocaleString();
                    const sizeMB = Math.round((metadata.size || 0) / (1024 * 1024) * 10) / 10;
                    const reason = metadata.backup_reason || metadata.reason || 'manual';
                    const domains = metadata.total_domains || metadata.domains?.length || 0;
                    
                    unifiedHtml += `
                        <div class="flex items-center justify-between p-3 bg-green-50 dark:bg-green-900/20 rounded-lg border border-green-200 dark:border-green-700">
                            <div class="flex-1 min-w-0">
                                <div class="text-sm font-medium text-gray-900 dark:text-white truncate">${backup.filename}</div>
                                <div class="text-xs text-gray-500 dark:text-gray-400 mt-1">${createdDate}</div>
                                <div class="flex items-center space-x-3 text-xs text-gray-400 dark:text-gray-500 mt-1">
                                    <span><i class="fas fa-weight mr-1"></i>${sizeMB}MB</span>
                                    <span><i class="fas fa-archive mr-1"></i>${domains} domains</span>
                                    <span><i class="fas fa-tag mr-1"></i>${reason}</span>
                                </div>
                            </div>
                            <div class="flex space-x-1 ml-2">
                                <button onclick="downloadBackup('unified', '${backup.filename}')" 
                                        class="p-2 text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300 hover:bg-blue-50 dark:hover:bg-blue-900/30 rounded transition-colors" 
                                        title="Download backup">
                                    <i class="fas fa-download text-sm"></i>
                                </button>
                                <button onclick="restoreBackup('unified', '${backup.filename}')" 
                                        class="p-2 text-green-600 hover:text-green-800 dark:text-green-400 dark:hover:text-green-300 hover:bg-green-50 dark:hover:bg-green-900/30 rounded transition-colors" 
                                        title="Restore backup">
                                    <i class="fas fa-undo text-sm"></i>
                                </button>
                                <button onclick="deleteBackup('unified', '${backup.filename}')" 
                                        class="p-2 text-red-600 hover:text-red-800 dark:text-red-400 dark:hover:text-red-300 hover:bg-red-50 dark:hover:bg-red-900/30 rounded transition-colors" 
                                        title="Delete backup">
                                    <i class="fas fa-trash text-sm"></i>
                                </button>
                            </div>
                        </div>
                    `;
                });
                
                if (backups.unified.length > 10) {
                    unifiedHtml += `
                        <div class="text-xs text-gray-500 dark:text-gray-400 text-center p-3 bg-gray-50 dark:bg-gray-700 rounded-lg">
                            <i class="fas fa-ellipsis-h mr-1"></i>
                            ${backups.unified.length - 10} more backups available
                        </div>
                    `;
                }
                
                unifiedBackupList.innerHTML = unifiedHtml;
            }
        }

        async function downloadBackup(type, filename) {
            // Only support unified backups
            if (type !== 'unified') {
                showMessage('Only unified backup download is supported.', 'error');
                return;
            }
            
            try {
                addDebugLog(`Downloading backup: ${filename}`, 'info');
                
                const response = await fetch(`/api/backups/download/unified/${filename}`, {
                    method: 'GET',
                    headers: {
                        'Authorization': `Bearer ${API_TOKEN}`
                    }
                });
                
                if (!response.ok) {
                    const errorText = await response.text();
                    throw new Error(`HTTP ${response.status}: ${errorText}`);
                }
                
                // Create download link
                const blob = await response.blob();
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = filename;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                window.URL.revokeObjectURL(url);
                
                addDebugLog(`Backup downloaded: ${filename}`, 'info');
                showMessage(`Backup downloaded: ${filename}`, 'success');
                
            } catch (error) {
                addDebugLog(`Error downloading backup: ${error.message}`, 'error');
                showMessage(`Error downloading backup: ${error.message}`, 'error');
            }
        }

        async function restoreBackup(type, filename) {
            // Only support unified backups
            if (type !== 'unified') {
                showMessage('Only unified backup restore is supported.', 'error');
                return;
            }
            
            if (!confirm(`Are you sure you want to restore from "${filename}"? This will atomically restore both settings and certificates, creating a backup of your current configuration first.`)) {
                return;
            }
            
            try {
                addDebugLog(`Restoring from backup: ${filename}`, 'info');
                
                const response = await fetch(`/api/backups/restore/unified`, {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${API_TOKEN}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        filename: filename,
                        create_backup_before_restore: true
                    })
                });
                
                if (!response.ok) {
                    const errorData = await response.text();
                    throw new Error(`HTTP ${response.status}: ${errorData}`);
                }
                
                const result = await response.json();
                
                addDebugLog(`Backup restored successfully from: ${filename}`, 'info');
                
                let successMessage = result.message || `Backup restored successfully!`;
                if (result.pre_restore_backup) {
                    successMessage += `\n\nA backup of the previous state was created: ${result.pre_restore_backup}`;
                }
                
                // Show immediate success message
                showMessage(`${successMessage}`, 'success');
                
                // Try to reload the settings data and refresh the UI
                try {
                    addDebugLog('Reloading settings after successful restore...', 'info');
                    
                    // Use loadSettings with suppressed error messages to avoid confusing the user
                    await loadSettings(true);
                    await refreshBackupList();
                    
                    addDebugLog('Settings reloaded successfully after restore', 'info');
                    showMessage(`✅ Backup restored and configuration reloaded successfully!`, 'success');
                    
                } catch (reloadError) {
                    addDebugLog(`Settings reload failed after successful restore: ${reloadError.message}`, 'warn');
                    showMessage(`✅ Backup restored successfully! Please refresh the page to see all changes.`, 'success');
                    
                    // Fallback to page reload after a delay
                    setTimeout(() => {
                        addDebugLog('Auto-refreshing page after restore...', 'info');
                        window.location.reload();
                    }, 3000);
                }
                
            } catch (error) {
                addDebugLog(`Error during backup restore: ${error.message}`, 'error');
                showMessage(`❌ Error restoring backup: ${error.message}`, 'error');
            }
        }

        async function deleteBackup(type, filename) {
            // Only support unified backups
            if (type !== 'unified') {
                showMessage('Only unified backup deletion is supported.', 'error');
                return;
            }
            
            if (!confirm(`Are you sure you want to delete the backup "${filename}"?\n\nThis action cannot be undone.`)) {
                return;
            }
            
            try {
                addDebugLog(`Deleting backup: ${filename}`, 'info');
                
                const response = await fetch(`/api/backups/delete/unified/${filename}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${API_TOKEN}`
                    }
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const result = await response.json();
                
                if (result.message) {
                    addDebugLog(`Backup deleted successfully: ${filename}`, 'info');
                    showMessage(`Backup "${filename}" deleted successfully!`, 'success');
                    
                    // Refresh backup list
                    await refreshBackupList();
                } else {
                    throw new Error(result.error || 'Failed to delete backup');
                }
                
            } catch (error) {
                addDebugLog(`Error deleting backup: ${error.message}`, 'error');
                showMessage(`Error deleting backup: ${error.message}`, 'error');
            }
        }

        // Load backup list on page load
        document.addEventListener('DOMContentLoaded', function() {
            // Load backup list after a short delay to let other elements load first
            setTimeout(() => {
                refreshBackupList();
            }, 1000);
        });

        // CA PROVIDER MANAGEMENT FUNCTIONS
        function toggleCAProviderConfig() {
            const caProvider = document.getElementById('default-ca').value;
            const configs = document.querySelectorAll('[id$="-config"]');
            
            // Hide all CA configuration panels
            const caConfigs = ['letsencrypt-config', 'digicert-config', 'private-ca-config'];
            caConfigs.forEach(configId => {
                const element = document.getElementById(configId);
                if (element) {
                    element.style.display = 'none';
                }
            });
            
            // Show the selected CA configuration panel
            const selectedConfigId = caProvider + '-config';
            const selectedConfig = document.getElementById(selectedConfigId);
            if (selectedConfig) {
                selectedConfig.style.display = 'block';
            }
            
            // Update hint text based on selected CA
            const hintElement = document.getElementById('ca-test-hint');
            if (hintElement) {
                switch (caProvider) {
                    case 'letsencrypt':
                        hintElement.textContent = 'Enter your email address and test Let\'s Encrypt connection';
                        break;
                    case 'digicert':
                        hintElement.textContent = 'Enter ACME URL, EAB credentials, and email, then test DigiCert connection';
                        break;
                    case 'private_ca':
                        hintElement.textContent = 'Enter your ACME directory URL and email, then test Private CA connection';
                        break;
                    default:
                        hintElement.textContent = 'Select a CA provider and fill in required fields, then test the connection';
                }
            }
        }

        async function testCAProvider() {
            const caProvider = document.getElementById('default-ca').value;
            let config = {};
            let missingFields = [];
            
            if (caProvider === 'letsencrypt') {
                const email = document.getElementById('letsencrypt-email').value;
                if (!email.trim()) {
                    missingFields.push('Email');
                }
                config = {
                    environment: document.getElementById('letsencrypt-environment').value,
                    email: email
                };
            } else if (caProvider === 'digicert') {
                const acmeUrl = document.getElementById('digicert-acme-url').value;
                const eabKid = document.getElementById('digicert-eab-kid').value;
                const eabHmac = document.getElementById('digicert-eab-hmac').value;
                const email = document.getElementById('digicert-email').value;
                
                if (!acmeUrl.trim()) missingFields.push('ACME URL');
                if (!eabKid.trim()) missingFields.push('EAB Key ID');
                if (!eabHmac.trim()) missingFields.push('EAB HMAC Key');
                if (!email.trim()) missingFields.push('Email');
                
                config = {
                    acme_url: acmeUrl,
                    eab_kid: eabKid,
                    eab_hmac: eabHmac,
                    email: email
                };
            } else if (caProvider === 'private_ca') {
                const acmeUrl = document.getElementById('private-ca-acme-url').value;
                const email = document.getElementById('private-ca-email').value;
                
                if (!acmeUrl.trim()) missingFields.push('ACME URL');
                if (!email.trim()) missingFields.push('Email');
                
                config = {
                    acme_url: acmeUrl,
                    ca_cert: document.getElementById('private-ca-cert').value,
                    eab_kid: document.getElementById('private-ca-eab-kid').value,
                    eab_hmac: document.getElementById('private-ca-eab-hmac').value,
                    email: email
                };
            }

            // Validate required fields
            if (missingFields.length > 0) {
                showMessage(`Please fill in the following required fields: ${missingFields.join(', ')}`, 'error');
                return;
            }

            // Show loading state
            const testButton = document.querySelector('button[onclick="testCAProvider()"]');
            const originalText = testButton.innerHTML;
            testButton.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i> Testing...';
            testButton.disabled = true;

            try {
                const response = await fetch('/api/settings/test-ca-provider', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${API_HEADERS.Authorization.replace('Bearer ', '')}`
                    },
                    body: JSON.stringify({
                        ca_provider: caProvider,
                        config: config
                    })
                });

                const result = await response.json();
                
                if (response.ok && result.success) {
                    showMessage(`✅ CA connection test successful! ${result.message}`, 'success');
                } else {
                    const errorMsg = result.message || result.error || 'Unknown error occurred';
                    showMessage(`❌ CA connection test failed: ${errorMsg}`, 'error');
                }
            } catch (error) {
                console.error('Error testing CA provider:', error);
                showMessage('❌ Error testing CA provider connection. Please check your network connection.', 'error');
            } finally {
                // Restore button state
                testButton.innerHTML = originalText;
                testButton.disabled = false;
            }
        }

        // STORAGE BACKEND MANAGEMENT FUNCTIONS
        function toggleStorageBackendConfig() {
            const backend = document.getElementById('storage-backend').value;
            const configs = document.querySelectorAll('.storage-config');
            
            // Hide all configuration panels
            configs.forEach(config => {
                config.style.display = 'none';
            });
            
            // Map backend names to their corresponding config div IDs
            const backendToConfigId = {
                'local_filesystem': 'storage-local-config',
                'azure_keyvault': 'storage-azure-config',
                'aws_secrets_manager': 'storage-aws-config',
                'hashicorp_vault': 'storage-vault-config',
                'infisical': 'storage-infisical-config'
            };
            
            // Show the selected configuration panel
            const configId = backendToConfigId[backend];
            if (configId) {
                const selectedConfig = document.getElementById(configId);
                if (selectedConfig) {
                    selectedConfig.style.display = 'block';
                    console.log(`Showing storage config for ${backend}: ${configId}`);
                } else {
                    console.error(`Storage config element not found: ${configId}`);
                }
            } else {
                console.error(`Unknown storage backend: ${backend}`);
            }
        }

        function testStorageBackend() {
            const backend = document.getElementById('storage-backend').value;
            const config = getStorageBackendConfig(backend);
            
            console.log('Testing storage backend:', backend);
            console.log('Configuration:', config);
            console.log('API Token available:', !!API_TOKEN);
            console.log('API Headers:', API_HEADERS);
            
            if (!validateStorageConfig(backend, config)) {
                console.log('Validation failed for config:', config);
                showMessage('Please fill in all required fields for the selected storage backend.', 'error');
                return;
            }
            
            showMessage('Testing storage backend connection...', 'info');
            
            const requestData = {
                backend: backend,
                config: config
            };
            
            console.log('Sending request data:', requestData);
            
            fetch('/api/storage/test', {
                method: 'POST',
                headers: API_HEADERS,
                body: JSON.stringify(requestData)
            })
            .then(response => {
                console.log('Response status:', response.status);
                console.log('Response headers:', response.headers);
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                return response.json();
            })
            .then(data => {
                console.log('Response data:', data);
                
                if (data.success) {
                    showMessage(`✓ ${data.message}`, 'success');
                } else if (data.message) {
                    showMessage(`✗ ${data.message}`, 'error');
                } else if (data.error) {
                    showMessage(`✗ ${data.error}`, 'error');
                } else {
                    showMessage('✗ Unknown error occurred', 'error');
                }
            })
            .catch(error => {
                console.error('Storage backend test error:', error);
                showMessage(`Failed to test storage backend connection: ${error.message}`, 'error');
            });
        }

        function getStorageBackendConfig(backend) {
            const config = {};
            
            switch (backend) {
                case 'local_filesystem':
                    config.cert_dir = document.getElementById('storage-cert-dir').value || 'certificates';
                    break;
                    
                case 'azure_keyvault':
                    config.vault_url = document.getElementById('azure-vault-url').value;
                    config.tenant_id = document.getElementById('azure-tenant-id').value;
                    config.client_id = document.getElementById('azure-client-id').value;
                    config.client_secret = document.getElementById('azure-client-secret').value;
                    break;
                    
                case 'aws_secrets_manager':
                    config.region = document.getElementById('aws-region').value || 'us-east-1';
                    config.access_key_id = document.getElementById('aws-access-key-id').value;
                    config.secret_access_key = document.getElementById('aws-secret-access-key').value;
                    break;
                    
                case 'hashicorp_vault':
                    config.vault_url = document.getElementById('vault-url').value;
                    config.vault_token = document.getElementById('vault-token').value;
                    config.mount_point = document.getElementById('vault-mount-point').value || 'secret';
                    config.engine_version = document.getElementById('vault-engine-version').value;
                    break;
                    
                case 'infisical':
                    config.site_url = document.getElementById('infisical-site-url').value || 'https://app.infisical.com';
                    config.client_id = document.getElementById('infisical-client-id').value;
                    config.client_secret = document.getElementById('infisical-client-secret').value;
                    config.project_id = document.getElementById('infisical-project-id').value;
                    config.environment = document.getElementById('infisical-environment').value || 'prod';
                    break;
            }
            
            return config;
        }

        function validateStorageConfig(backend, config) {
            switch (backend) {
                case 'local_filesystem':
                    return config.cert_dir && config.cert_dir.trim() !== '';
                    
                case 'azure_keyvault':
                    return config.vault_url && config.tenant_id && config.client_id && config.client_secret;
                    
                case 'aws_secrets_manager':
                    return config.access_key_id && config.secret_access_key;
                    
                case 'hashicorp_vault':
                    return config.vault_url && config.vault_token;
                    
                case 'infisical':
                    return config.client_id && config.client_secret && config.project_id;
                    
                default:
                    return false;
            }
        }

        function loadCAProviderSettings(settings) {
            // Set default CA provider
            const defaultCA = settings.default_ca || 'letsencrypt';
            document.getElementById('default-ca').value = defaultCA;
            toggleCAProviderConfig();
            
            // Load CA provider configurations
            const caProviders = settings.ca_providers || {};
            
            // Load Let's Encrypt settings
            const letsencryptConfig = caProviders.letsencrypt || {};
            if (letsencryptConfig.environment) {
                document.getElementById('letsencrypt-environment').value = letsencryptConfig.environment;
            }
            if (letsencryptConfig.email) {
                document.getElementById('letsencrypt-email').value = letsencryptConfig.email;
            }
            
            // Load DigiCert settings
            const digicertConfig = caProviders.digicert || {};
            if (digicertConfig.acme_url) {
                document.getElementById('digicert-acme-url').value = digicertConfig.acme_url;
            }
            if (digicertConfig.eab_kid) {
                document.getElementById('digicert-eab-kid').value = digicertConfig.eab_kid;
            }
            // Don't populate HMAC key for security reasons - user needs to re-enter
            if (digicertConfig.email) {
                document.getElementById('digicert-email').value = digicertConfig.email;
            }
            
            // Load Private CA settings
            const privateCaConfig = caProviders.private_ca || {};
            if (privateCaConfig.acme_url) {
                document.getElementById('private-ca-acme-url').value = privateCaConfig.acme_url;
            }
            if (privateCaConfig.ca_cert) {
                document.getElementById('private-ca-cert').value = privateCaConfig.ca_cert;
            }
            if (privateCaConfig.eab_kid) {
                document.getElementById('private-ca-eab-kid').value = privateCaConfig.eab_kid;
            }
            // Don't populate HMAC key for security reasons - user needs to re-enter
            if (privateCaConfig.email) {
                document.getElementById('private-ca-email').value = privateCaConfig.email;
            }
        }

        function loadStorageBackendSettings(settings) {
            const storageConfig = settings.certificate_storage || {};
            const backend = storageConfig.backend || 'local_filesystem';
            
            // Set backend selection
            document.getElementById('storage-backend').value = backend;
            toggleStorageBackendConfig();
            
            // Load backend-specific configuration
            switch (backend) {
                case 'local_filesystem':
                    if (storageConfig.cert_dir) {
                        document.getElementById('storage-cert-dir').value = storageConfig.cert_dir;
                    }
                    break;
                    
                case 'azure_keyvault':
                    const azureConfig = storageConfig.azure_keyvault || {};
                    document.getElementById('azure-vault-url').value = azureConfig.vault_url || '';
                    document.getElementById('azure-tenant-id').value = azureConfig.tenant_id || '';
                    document.getElementById('azure-client-id').value = azureConfig.client_id || '';
                    // Don't populate client_secret for security
                    break;
                    
                case 'aws_secrets_manager':
                    const awsConfig = storageConfig.aws_secrets_manager || {};
                    document.getElementById('aws-region').value = awsConfig.region || 'us-east-1';
                    document.getElementById('aws-access-key-id').value = awsConfig.access_key_id || '';
                    // Don't populate secret_access_key for security
                    break;
                    
                case 'hashicorp_vault':
                    const vaultConfig = storageConfig.hashicorp_vault || {};
                    document.getElementById('vault-url').value = vaultConfig.vault_url || '';
                    document.getElementById('vault-mount-point').value = vaultConfig.mount_point || 'secret';
                    document.getElementById('vault-engine-version').value = vaultConfig.engine_version || 'v2';
                    // Don't populate vault_token for security
                    break;
                    
                case 'infisical':
                    const infisicalConfig = storageConfig.infisical || {};
                    document.getElementById('infisical-site-url').value = infisicalConfig.site_url || 'https://app.infisical.com';
                    document.getElementById('infisical-project-id').value = infisicalConfig.project_id || '';
                    document.getElementById('infisical-environment').value = infisicalConfig.environment || 'prod';
                    // Don't populate client credentials for security
                    break;
            }
        }

        function collectCAProviderSettings() {
            const caProviders = {};
            
            // Let's Encrypt configuration
            caProviders.letsencrypt = {
                environment: document.getElementById('letsencrypt-environment').value || 'production',
                email: document.getElementById('letsencrypt-email').value || ''
            };
            
            // DigiCert configuration
            caProviders.digicert = {
                acme_url: document.getElementById('digicert-acme-url').value || 'https://acme.digicert.com/v2/acme/directory',
                eab_kid: document.getElementById('digicert-eab-kid').value || '',
                eab_hmac: document.getElementById('digicert-eab-hmac').value || '',
                email: document.getElementById('digicert-email').value || ''
            };
            
            // Private CA configuration
            caProviders.private_ca = {
                acme_url: document.getElementById('private-ca-acme-url').value || '',
                ca_cert: document.getElementById('private-ca-cert').value || '',
                eab_kid: document.getElementById('private-ca-eab-kid').value || '',
                eab_hmac: document.getElementById('private-ca-eab-hmac').value || '',
                email: document.getElementById('private-ca-email').value || ''
            };
            
            return caProviders;
        }

        function collectStorageBackendSettings() {
            const backend = document.getElementById('storage-backend').value;
            const config = getStorageBackendConfig(backend);
            
            return {
                backend: backend,
                ...config
            };
        }

        function showStorageMigrationModal() {
            // Create migration modal dynamically
            const modal = document.createElement('div');
            modal.id = 'storageMigrationModal';
            modal.className = 'fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50';
            modal.innerHTML = `
                <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white dark:bg-gray-800">
                    <div class="mt-3">
                        <div class="flex items-center justify-between mb-4">
                            <h3 class="text-lg font-medium text-gray-900 dark:text-white">
                                <i class="fas fa-exchange-alt mr-2"></i>Certificate Storage Migration
                            </h3>
                            <button type="button" onclick="closeStorageMigrationModal()" class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                        <div class="mb-4">
                            <p class="text-sm text-gray-600 dark:text-gray-400">
                                This will migrate all existing certificates from the current storage backend to the newly configured backend.
                            </p>
                            <div class="mt-3 p-3 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-700 rounded-md">
                                <div class="flex">
                                    <i class="fas fa-exclamation-triangle text-yellow-400 mt-0.5 mr-2"></i>
                                    <div class="text-sm text-yellow-800 dark:text-yellow-200">
                                        <strong>Important:</strong> This operation will copy certificates to the new backend. 
                                        Original certificates will remain in the current location until manually removed.
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="flex justify-end space-x-3">
                            <button type="button" onclick="closeStorageMigrationModal()" 
                                    class="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-600 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-md">
                                Cancel
                            </button>
                            <button type="button" onclick="performStorageMigration()" 
                                    class="px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-md">
                                <i class="fas fa-play mr-1"></i>Start Migration
                            </button>
                        </div>
                    </div>
                </div>
            `;
            document.body.appendChild(modal);
        }

        function closeStorageMigrationModal() {
            const modal = document.getElementById('storageMigrationModal');
            if (modal) {
                modal.remove();
            }
        }

        function performStorageMigration() {
            const currentBackend = document.getElementById('storage-backend').value;
            const newConfig = collectStorageBackendSettings();
            
            // Validate new configuration first
            if (!validateStorageConfig(newConfig.backend, newConfig)) {
                showMessage('Please configure and test the new storage backend before migrating.', 'error');
                return;
            }
            
            showMessage('Starting certificate migration...', 'info');
            closeStorageMigrationModal();
            
            fetch('/api/storage/migrate', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${getAuthToken()}`
                },
                body: JSON.stringify({
                    source_backend: currentBackend,
                    target_config: newConfig
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showMessage(`Migration completed successfully. ${data.migrated_count || 0} certificates migrated.`, 'success');
                } else {
                    showMessage(`Migration failed: ${data.message || 'Unknown error'}`, 'error');
                }
            })
            .catch(error => {
                console.error('Migration error:', error);
                showMessage('Failed to perform storage migration.', 'error');
            });
        }
    </script>
</body>
</html>
